zoukankan      html  css  js  c++  java
  • Hibernate工具类_抽取重复核心代码

    问题:在Hibernate中每次执行一次操作总是需要加载核心配置文件,获取连接池等等都是重复动作,所以抽取出来

    解决:

    package com.xxx.utils;
    /**
    *Hibernate的工具类
    *@author cxh
    */
    
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HiberUtils {
    //    1.创建一个session回话工厂,以单例模式管理(简单的获取session第一种)
        private static SessionFactory sessionFactory;
        
    //    2.ThreadLocal存储session,一开始直接将session绑到当前线程,后面直接来获取线程中的session(第二种)
        private static ThreadLocal<Session> currentSession = new ThreadLocal<Session>(); 
        
        //初始化获取session会话工厂
        static {
            try {
                sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
            } catch (HibernateException e){
                e.printStackTrace();
                throw new HibernateException("初始化会话工厂失败");
            }
        }
        
    //    获取单例会话工厂
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
        
    //    获取session对象
        public static Session openSession() {
            return sessionFactory.openSession();
        }
        
    //    获取绑定到线程里面的session,如果获取不到就创建一个新的线程去绑定session.这里面要想session对象的生命周期与当前线程绑定,还需要在hibernate配置文件里面配置current_session_context_class属性,设置为thread
        public Session getCurrentThreadSession() {
    //        获取线程中的session
            Session s = currentSession.get();
            if(s == null) {
    //            创建一个新的session
                s = sessionFactory.openSession();
    //            将新的session与当前线程绑定
                currentSession.set(s);
            }
    //        不为空,当前线程有session,直接返回
            return s;
        }
        
    //    关闭当前线程的session
        public static void closeCurrentThreadSession() {
    //        获取当前线程绑定的session对象
            Session s = currentSession.get();
    //        当前线程有session对象,且该对象不为空,需要关闭
            if(s != null) {
                s.close();
            }
            currentSession.set(null);
        }
        
    //    3.hibernate中底层已经帮你封装了将session与当前线程绑定的方法
        public static Session getCurrentSession() {
            return sessionFactory.getCurrentSession();
        }
        
        //上面两种获取线程里面的session都可以直接调用该封装方法进行关闭
        public static void closeSession() throws HibernateException {
            sessionFactory.getCurrentSession().close();
        }
        
    }

      

  • 相关阅读:
    leetcode:Valid Parentheses(有效括号匹配)
    leetcode:Remove Nth Node From End of List (移除从尾部数的第N个节点)
    leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)
    leetcode:4Sums(四个数相加的和)
    leetcode:3Sum Closest
    leetcode:3Sum (三个数的和)
    leetcode:Longest Common Prefix(取最长字符串前缀)
    php数据访问
    PHP 基础知识测试题
    面相对象设计模式
  • 原文地址:https://www.cnblogs.com/ends-earth/p/10762270.html
Copyright © 2011-2022 走看看