工具类:mybatis中使用Threadlocal开启session及关闭session

1、线程容器,给线程绑定一个Object 内容,后只要线程不变,可以随时取出.
1.1 改变线程,无法取出内容.
1 final ThreadLocal threadLocal = new ThreadLocal<>();
2 threadLocal.set("测试");
3 new Thread(){
4     public void run() {
5         String result = threadLocal.get();
6         System.out.println("结果:"+result);
7     };
8 }.start();
2、使用Threadlocal简化开发
2.1定义工具类
    将SqlSession创建出来,存放到Threadlocal中,需要时再从中取出
 1 package com.test.util;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 
11 public class MybatisUtil {
12 
13     //工厂
14     private static SqlSessionFactory factory;
15     //线程容器
16     private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
17     
18     
19     static{
20         try {
21             InputStream is = Resources.getResourceAsStream("mybatis.xml");
22             factory = new SqlSessionFactoryBuilder().build(is);
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26     }
27     /**
28      * 获取session
29      * 从线程容器中获取,没有则创建session在存放到线程容器中
30      * @return
31      */
32     public static SqlSession getSession(){
33         SqlSession sqlSession = tl.get();
34         if(sqlSession == null){
35             sqlSession = factory.openSession();
36             tl.set(sqlSession);
37         }
38         return tl.get();
39     }
40     
41     /**
42      * 关闭session
43      * 从容器线程中获取session,有则关闭,且将线程容器的session清空
44      */
45     public static void closeSession(){
46         SqlSession sqlSession = tl.get();
47         if(sqlSession != null){
48             sqlSession.close();
49         }
50         tl.set(null);
51     }
52 }
将工厂的产生改成单例模式
 1 package com.text.util;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.logging.Level;
 6 import java.util.logging.Logger;
 7 
 8 import org.apache.ibatis.io.Resources;
 9 import org.apache.ibatis.session.SqlSession;
10 import org.apache.ibatis.session.SqlSessionFactory;
11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
12 
13 
14 public class MybatisUtil {
15 
16     //工厂
17     private static SqlSessionFactory factory;
18     //类线程锁
19     private static final Class CLASS_LOCK = MybatisUtil.class;
20     //线程容器
21     private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
22     //构造器私有化
23     private MybatisUtil(){}
24     
25     public static SqlSessionFactory initSqlSessionFactory(){
26         String resource = "mybatis.xml";
27         InputStream is = null;
28         try {
29             is = Resources.getResourceAsStream(resource);
30         } catch (IOException e) {
31             Logger.getLogger(MybatisUtil.class.getName()).log(Level.SEVERE, null, e);
32         }
33         synchronized (CLASS_LOCK) {
34             if(null == factory){
35                 factory = new SqlSessionFactoryBuilder().build(is);
36             }
37         }
38         return factory;
39     }
40     
41     /**
42      * 获取session
43      * 从线程容器中获取,没有则创建session在存放到线程容器中
44      * @return
45      */
46     public static SqlSession getSession(){
47         SqlSession sqlSession = tl.get();
48         if(sqlSession == null){
49             if(factory == null){
50                 initSqlSessionFactory();
51             }
52             sqlSession = factory.openSession();
53             tl.set(sqlSession);
54         }
55         return tl.get();
56     }
57     
58     /**
59      * 关闭session
60      * 从容器线程中获取session,有则关闭,且将线程容器的session清空
61      */
62     public static void closeSession(){
63         SqlSession sqlSession = tl.get();
64         if(sqlSession != null){
65             sqlSession.close();
66         }
67         tl.set(null);
68     }
69 }

 

 
2.2 定义过滤器
    过滤器可以在调用方法前及方法后添加代码
 1 package com.test.filter;
 2 
 3 import java.io.IOException;
 4 
 5 import java.io.InputStream;
 6 
 7 import javax.servlet.Filter;
 8 import javax.servlet.FilterChain;
 9 import javax.servlet.FilterConfig;
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletRequest;
12 import javax.servlet.ServletResponse;
13 import javax.servlet.annotation.WebFilter;
14 
15 import org.apache.ibatis.io.Resources;
16 import org.apache.ibatis.session.SqlSession;
17 import org.apache.ibatis.session.SqlSessionFactory;
18 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
19 
20 import com.test.util.MyBatisUtil;
21 
22 
23 /**
24  * 最开始是由Spring框架提出的.整合Hibernate框架是使用的是OpenSessionInView
25  * 
26  * 
27  * @author Administrator
28  *
29  */
30 @WebFilter("/*")
31 public class OpenSessionInView implements Filter{
32 
33     @Override
34     public void init(FilterConfig filterconfig) throws ServletException {
35         // TODO Auto-generated method stub
36     }
37 
38     @Override
39     public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
40             throws IOException, ServletException {
41 //        InputStream is = Resources.getResourceAsStream("mybatis.xml");
42 //        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
43 //        SqlSession session = factory.openSession();        
44         SqlSession session = MyBatisUtil.getSession();
45         try {
46             filterchain.doFilter(servletrequest, servletresponse);
47             session.commit();
48         } catch (Exception e) {
49             session.rollback();
50             e.printStackTrace();
51         }finally{
52             MyBatisUtil.closeSession();
53         }
54 //        session.commit();
55 //        session.close();
56     }
57 
58     @Override
59     public void destroy() {
60         // TODO Auto-generated method stub    
61     }
62 }

 

 
posted @ 2019-02-15 10:56  夜小十五天  阅读(1546)  评论(0编辑  收藏  举报