将session管理封装在一个类中,便于放到spring IOC中作为
全局单例管理。
class="java" name="code">
package example;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisSessionMgr {
SqlSessionFactory sqlfactory;
public void init() throws IOException {
String resource = "mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resource);
sqlfactory = new SqlSessionFactoryBuilder().build(in);
}
public SqlSession openSession() {
SqlSession session = sqlfactory.openSession();
return session;
}
}
因为Mybatis中,SqlSession需要在每次执行sql的时候创建,执行完后关闭。因此,这里用一个简单的抽象类+内部
接口,封装了SqlSession的创建与关闭。所有具体负责数据库操作的DAO都集成该抽象类,就不需要自己去维护session了,避免因为忘记在finally中加session.close导致session没有释放。
package example.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import example.MybatisSessionMgr;
public abstract class AbstractBatisDAO {
protected static Log log = LogFactory.getLog(AbstractBatisDAO.class);
public interface SqlCaller {
public Object doWith(SqlSession session);
}
private MybatisSessionMgr sessionMgr;
public Object process(SqlCaller caller) {
SqlSession session = sessionMgr.openSession();
Object res = null;
try {
res = caller.doWith(session);
session.commit();
} catch (Exception e) {
session.rollback();
log.error(e);
} finally {
session.close();
}
return res;
}
public void setSessionMgr(MybatisSessionMgr sessionMgr) {
this.sessionMgr = sessionMgr;
}
}