XCMercy 2019-11-30
1. 线程容器,给线程绑定一个 Object 内容,后只要线程不变,可以随时取出.
1.1 改变线程,无法取出内容.
2. 语法示例
final ThreadLocal<String> threadLocal = new ThreadLocal<>(); threadLocal.set("测试"); new Thread(){public void run() { String result = threadLocal.get(); System.out.println("结果:"+result); }; }.start();
3. 封装工具类
public class MyBatisUtil { //factory实例化的过程是一个比较耗费性能的过程. //保证有且只有一个factory private static SqlSessionFactory factory; private static ThreadLocal<SqlSession> tl = new ThreadLocal<>(); static{ try { InputStream is = Resources.getResourceAsStream("mybatis.xml"); factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 获取SqlSession的方法 */ public static SqlSession getSession(){ SqlSession session = tl.get(); if(session==null){ tl.set(factory.openSession()); } return tl.get(); } public static void closeSession(){ SqlSession session = tl.get(); if(session!=null){ session.close(); } tl.set(null); } }
4. 封装Filter类
package com.bjsxt.filter; import java.io.IOException; import java.io.InputStream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; 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 com.bjsxt.util.MyBatisUtil; /** * 最开始是由Spring框架提出的.整合Hibernate框架是使用的是OpenSessionInView * * * @author Administrator * */ @WebFilter("/*") public class OpenSessionInView implements Filter{ @Override public void init(FilterConfig filterconfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException { // InputStream is = Resources.getResourceAsStream("mybatis.xml"); // SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); // SqlSession session = factory.openSession(); SqlSession session = MyBatisUtil.getSession(); try { filterchain.doFilter(servletrequest, servletresponse); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ MyBatisUtil.closeSession(); } // session.commit(); // session.close(); } @Override public void destroy() { // TODO Auto-generated method stub } }
5. 使用
public class LogServiceImpl implements LogService{ @Override public int ins(Log log) { SqlSession session = MyBatisUtil.getSession(); LogMapper mapper = session.getMapper(LogMapper.class); return mapper.ins(log); } }