一、hibernate获取

 

 二、配置 / util编写

1.hbm.xml

1 <!-- 开启session的线程管理模式 -->
2     <property name="current_session_context_class">thread</property>

 

2.util

 

 1 package com.sdkj.hibernate.dao;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.boot.MetadataSources;
 6 import org.hibernate.cfg.Configuration;
 7 
 8 /**
 9  * @Author wangshuo
10  * @Date 2022/4/10, 22:25
11  * util 获取session
12  */
13 public class HibernateUtil {
14 
15     //获取hibernate与数据库连接的会话对象,在整个应用的作用域中应该只有一个
16     //此工具类应该做成单例模式
17     private static HibernateUtil hibernateUtil = null;
18 
19     //私有化构造方法
20     private HibernateUtil(){}
21 
22     //提供一个公共的静态的方法,返回公共类的实例对象
23     public static HibernateUtil getInstance(){
24 
25         if (hibernateUtil == null){
26             hibernateUtil = new HibernateUtil();
27         }
28         return hibernateUtil;
29     }
30 
31     //获取sessionFactory
32     public SessionFactory getSessionFactory(){
33 
34         return (new MetadataSources(new Configuration().configure()
35                 .getStandardServiceRegistryBuilder().build()).buildMetadata().buildSessionFactory());
36     }
37 
38     //获取session
39     public Session getSession(){
40 
41         return getSessionFactory().getCurrentSession();//获取与当前线程绑定的session
42     }
43 }

3.dao方法demo

 1 package com.sdkj.hibernate.dao;
 2 
 3 import com.sdkj.hibernate.domain.HTeacherEntity;
 4 import org.hibernate.Session;
 5 
 6 /**
 7  * @Author wangshuo
 8  * @Date 2022/4/10, 22:21
 9  * 教师实体dao层
10  */
11 public class TeacherDao {
12 
13 
14     public void add(HTeacherEntity teacherEntity){
15 
16         Session session = HibernateUtil.getInstance().getSession();
17         session.save(teacherEntity);
18     }
19 }