Mybatis抽取SqlSessionFactory方法复用
抽取成工具类的目的,解决繁琐的创建步骤,提高效率。
package cn.itxiaoli.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
private static SqlSession sqlSession = null;
private static final SqlSessionFactory sqlSessionFactory;
static {
InputStream resourceAsStream = null;
try {
resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
}
@SuppressWarnings("unchecked")
public static Object getMapper(Class T) {
sqlSession = sqlSessionFactory.openSession(true);
return sqlSession.getMapper(T);
}
public static void sqlSessionClose() {
sqlSession.close();
}
}
/**
* 测试方法
* 添加品牌信息
*
* @param brand
*/
public void add(Brand brand) {
BrandMapper mapper = (BrandMapper)SqlSessionFactoryUtils.getMapper(BrandMapper.class);
mapper.add(brand);
SqlSessionFactoryUtils.sqlSessionClose();
}