All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.coder.jdbc.support.DaoSupport Maven / Gradle / Ivy

package cn.coder.jdbc.support;

import java.sql.SQLException;

import cn.coder.jdbc.SqlSession;
import cn.coder.jdbc.SqlSessionFactory;
import cn.coder.jdbc.SqlTranction;

public abstract class DaoSupport {

	private SqlSessionFactory sessionFactory;

	protected SqlSessionFactory getSessionFactory(String source) {
		if (sessionFactory == null) {
			//不是Spring创建则使用内部创建好的Factory
			sessionFactory = SqlSessionFactory.getInnerFactory(source);
		}
		if (sessionFactory == null)
			throw new NullPointerException("Can not found any session factory");
		return sessionFactory;
	}

	/**
	 * Spring对sessionFactory赋值接口
	 * 
	 * @param sessionFactory
	 */
	public void setSessionFactory(SqlSessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected SqlSession jdbc() {
		return jdbc(SqlSessionFactory.DEFAULT_SOURCE);
	}

	protected SqlSession jdbc(String source) {
		return getSessionFactory(source).cachedSession();
	}

	protected boolean tran(Run run) {
		return tran(SqlSessionFactory.DEFAULT_SOURCE, run);
	}

	public boolean exist(Object obj) {
		return jdbc().exist(obj);
	}

	public boolean insert(Object obj) {
		return jdbc().insert(obj);
	}

	public boolean update(Object obj) {
		return jdbc().update(obj);
	}

	public boolean delete(Object obj) {
		return jdbc().delete(obj);
	}

	protected boolean tran(String source, Run run) {
		SqlSession session = jdbc(source);
		SqlTranction tran = null;
		try {
			tran = session.beginTranction();
			run.exec(session);
			tran.commit();
			return true;
		} catch (Exception e) {
			if (tran != null)
				tran.rollback(e);
			return false;
		}
	}

	protected interface Run {
		// 执行事务
		void exec(final SqlSession session) throws SQLException;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy