时间:2021-07-01 10:21:17 帮助过:30人阅读
2、hibernateUtil类
package com.project.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static Configuration cfg = null; private static StandardServiceRegistry registry = null; private static SessionFactory factory = null; private static ThreadLocal<Session> sessionLocal = null; static{ //1、读取hibernate.cfg.xml配置文件 cfg = new Configuration().configure(); //2、创建服务注册器 registry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); //3、新建sessionFactory对象 //sessionFactory是一个重量级对象,在一个应用只需一个即可,是进程级别的对象,可以在集群中使用,操作完后不释放 factory = cfg.buildSessionFactory(registry); //4、创建threadLocal(成员私有,线程安全) sessionLocal = new ThreadLocal<>(); } //获取session对象 public static Session getSession(){ //session不为空且session未被打开时,session设置为null if(sessionLocal.get() != null && !sessionLocal.get().isOpen()){ sessionLocal.set(null); } //session为null时,创建session if(sessionLocal.get() == null){ sessionLocal.set(factory.openSession()); } return sessionLocal.get(); } //关闭session public static void closeSession(){ if(sessionLocal.get() != null){ //session调用close不一定清除session对象 sessionLocal.get().close(); //所以sessionLocal中session对象设置为null sessionLocal.set(null); } } }
3、dao使用
package com.project.dao.impl; import java.util.List; import org.hibernate.Session; import com.project.dao.EmployeeDao; import com.project.pojo.Employee; import com.project.util.HibernateUtil; public class EmployeeDaoImpl implements EmployeeDao{ @Override public List<Employee> find() { /** * HibernateUtil.getSession()与filer中使用的是同一个session */ Session session = HibernateUtil.getSession(); List<Employee> list = session.createCriteria(Employee.class).list(); return list; } }
hibernate基础14:OpenSessionInView(抽取web访问时对数据库开关事务)
标签:cep row EDA 关闭 over 对象 hibernate stat private