public class MyBaitsView { //使用java提供的ThreadLocal类来存储SqlSession对象,方便同一线程获得sqlSession public static ThreadLocal<SqlSession> threadLocal=new ThreadLocal(); public static SqlSessionFactory factory; //初使化SqlSessionFactory工厂 static { try { InputStream is = Resources.getResourceAsStream("myBatis.xml"); factory=new SqlSessionFactoryBuilder().build(is); }catch(Exception e) { e.printStackTrace(); } } //获取SqlSession的方法,如果session 为空,则生成一个新的SqlSession public static SqlSession getSession() { SqlSession session=threadLocal.get(); if(session==null) { threadLocal.set(factory.openSession()); } return threadLocal.get(); } //关闭SqlSession public static void closeSession() { SqlSession session=threadLocal.get(); if(session!=null) { session.close(); } } }
@WebFilter("/*")
public class InsertFilter implements Filter{
@Override
public void destroy() { }
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
throws IOException, ServletException {
//获得当前线程的SqlSession对象
SqlSession session=MyBaitsView.getSession();
try {
//对请求进行处理
filter.doFilter(request, response);
}catch(Exception e) {
//如果出异常,则回滚
session.rollback();
e.printStackTrace();
}finally {
//提交事务,关闭SqlSession
session.commit();
MyBaitsView.closeSession();
}
}
@Override
public void init(FilterConfig arg0) throws ServletException { }
}
public class InsertServlet extends HttpServlet{ InsertService insertService=new InsertServiceImpl(); @Override public void service(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { request.setCharacterEncoding("utf-8"); Log log=new Log(); //获得表单数据 log.setAccountIn(request.getParameter("accountIn")); log.setAccountOut(request.getParameter("accountOut")); log.setMoney(Integer.parseInt(request.getParameter("money"))); //调用service层方法插入数据 int index = insertService.insert(log); System.out.println(index); } }
public class InsertServiceImpl implements InsertService{ @Override public int insert(Log log) { //获得SqlSession对象 SqlSession session=MyBaitsView.getSession(); LogMappery logMapper = session.getMapper(LogMappery.class); int index=logMapper.insert(log); return index; } }
MyBatis基础:使用java提供的ThreadLocal类优化代码
原文:https://www.cnblogs.com/lastingjava/p/9955441.html