• 管理Session


    1:把session和本地线程绑定在一起。

    1):创建一个sessionFactory。然后由它去创建session

    package com.hq.util;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    public class HibernateUtils {
        
        private HibernateUtils(){}
        
        private static HibernateUtils instance=new HibernateUtils();
        
        public static HibernateUtils getInstance(){
            return instance;
        }
        
        private SessionFactory sessionFactory;
        public SessionFactory getSessionFactory() {
            if (sessionFactory == null) {
                Configuration configuration = new Configuration().configure();
                ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                        .applySettings(configuration.getProperties())
                        .buildServiceRegistry();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            }
            return sessionFactory;
        }
        
        public Session getSession(){
            return getSessionFactory().getCurrentSession();
        }
    }

    使用:getCurrentSession()方法。

    2):通过单例的HibernateUtils来得到session

    public class DeptDao {
        public void save(Department dept){
            Session session=HibernateUtils.getInstance().getSession();
            System.out.println(session.hashCode());
    //        session.save(dept);
        }
        
    }

    3):在配置文件中配置

    <!-- 配置管理session的方法 -->
            <property name="current_session_context_class">thread</property>

    4):测试

    @org.junit.Test
        public void testSession(){
                    //获取 Session
                    //开启事务
                    Session session = HibernateUtils.getInstance().getSession();
                    System.out.println("-->" + session.hashCode());
                    Transaction transaction = session.beginTransaction();
                    DeptDao departmentDao = new DeptDao();
                    
                    Department dept = new Department();
                    dept.setName("ATGUIGU");
                    
                    departmentDao.save(dept);
                    departmentDao.save(dept);
                    departmentDao.save(dept);
                    
                    //若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了. 
                    transaction.commit();
                    System.out.println(session.isOpen()); 
        }
  • 相关阅读:
    内存溢出和内存泄漏的区别、产生原因以及解决方案
    HTTP1.0、HTTP1.1 和 HTTP2.0 的区别
    TCP, UDP, HTTP, HTTPS协议
    测试面试常见面试题汇总
    SDK测试方法
    App弱网测试工具--Qnet
    PerfDog性能狗移动端性能测试工具
    Jmeter作用域
    事务(转账功能)
    DBUtils
  • 原文地址:https://www.cnblogs.com/bulrush/p/7881697.html
Copyright © 2020-2023  润新知