Mybatis工具类封装成单例模式
Q:为什么要封装成单例模式?网上的封装方法不是整的挺好的吗?
A:我之前使用网上提供的封装方法,总是提示Communications link failure异常。项目刚开始运行良好,10分钟后springboot项目提示连接异常。我联想到之间封装JDBC为单例模式一点问题也没有。所以尝试改成单例模式之后,不会报错了。
MyBatisUntil.java
public class MyBatisUntil {
private static MyBatisUntil instance=new MyBatisUntil();
private MyBatisUntil(){}
public static MyBatisUntil getInstance(){
return instance;
}
public static SqlSession getSqlSession(boolean IsAutoComiit) throws IOException {
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is);
return sqlSessionFactory.openSession(IsAutoComiit);
}
//使用泛型封装getMapper
public static <T extends Object> T getMapper(Class<T> c) throws IOException {
SqlSession sqlSession = getSqlSession(true);
return sqlSession.getMapper(c);
}
}
怎么去调用单例模式的MyBatisUntil里面的功能?
第一步
MyBatisUntil myBatisUntil = MyBatisUntil.getInstance();
第二步
List<Object> get_AD_data=myBatisUntil.getSqlSession(true)
.getMapper(businessMapper.class)
.get_AD_data();