小狼最近在做mybatis的CURD,发现一个小狼不能接受的问题,当然,小狼是比较懒的,见不得冗余代码
每一个CURD操作,小狼都得写一遍下面的代码,一口老血吐出来了...
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); InputStream config = Resources .getResourceAsStream("mybatities-config.xml"); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder .build(config); SqlSession sqlSession = sqlSessionFactory.openSession();
为了小狼后半生幸福,决定了,写一个工具类
public class GetSqlSession { private static SqlSessionFactory sqlSessionFactory; private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>(); synchronized public static SqlSessionFactory getSqlSessionFactory() { try { InputStream isRef=GetSqlSession.class.getResourceAsStream("/DBMysql.properties"); Properties properties=new Properties(); properties.load(isRef); //Log.getLog().info("properties="+properties); if (sqlSessionFactory == null) { String resource = "mybatis-config.xml"; InputStream inputStream = Resources .getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream,properties); } else { } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sqlSessionFactory; } public static SqlSession getSqlSession() { SqlSession sqlSession = tl.get(); if (sqlSession == null) { sqlSession = getSqlSessionFactory() .openSession(); tl.set(sqlSession); } else { } //System.out.println("获得的sqlSession对象的hashCode:" + sqlSession.hashCode()); return sqlSession; } public static void commit() { if (tl.get() != null) { tl.get().commit(); tl.get().close(); tl.set(null); //System.out.println("提交了"); } } public static void rollback() { if (tl.get() != null) { tl.get().rollback(); tl.get().close(); tl.set(null); //System.out.println("回滚了"); } } }
SqlSession sqlSession = GetSqlSession.getSqlSession();大家可能发现一个问题,小狼这里写了一句
synchronized public static SqlSessionFactory getSqlSessionFactory() {
try {
InputStream isRef=GetSqlSession.class.getResourceAsStream("/DBMysql.properties");
Properties properties=new Properties();
properties.load(isRef);
//Log.getLog().info("properties="+properties);
if (sqlSessionFactory == null) {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources
.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream,properties);
} else {
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sqlSessionFactory;
}
这个小狼可以解释一下,小狼用的property,属性配置mybatis-config.xml,里面的参数,所以得读出property的文件内容,并与已经读出的mybatis-config.xml文件内容匹配,得到值,注入
写完了这么多,一口老血又咽回去了。。。
原文地址:http://blog.csdn.net/zhanglu1236789/article/details/45007685