小狼最近在做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("回滚了");
}
}
}
小狼上一次说了,sqlsessionFactory的生命周期是整个项目运行期间,他都会存在。但是我们采用单例懒汉模式,比较人性化。每一个线程都得使用一个sqlsession,并且sqlsession是不能共享的,它是线程不安全的,所以这就涉及到多线程的问题。我们采用ThreadLocal<SqlSession>,为每一个线程创建一个sqlsession副本,副本跟副本之间互相不影响。这样我们获得sqlsession对象的时候,直接这么写
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文件内容匹配,得到值,注入
写完了这么多,一口老血又咽回去了。。。