zl程序教程

您现在的位置是:首页 >  后端

当前栏目

hibernate中3个重要的类 Configuration SessionFactory Session

hibernate session 重要 configuration
2023-09-14 08:58:31 时间

配置类Configuration

主要负责管理hibernate的配置信息以及启动hibernate,在hibernate运行时,配置文件取读底层的配置信息,基本包括数据库驱动,url、username、password、dialect、show_sql、format_sql、mapping映射文件等等

配置文件一般放在src目录下

demo:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration 3.0.dtd">
    
<hibernate-configuration>
   <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        
        <property name="connection.username">root</property>
        
        <property name="connection.password">root</property>
        
        <property name="connection.url">jdbc:mysql://localhost:3306/helloworld</property>
        
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <property name="show_sql">true</property>
        
        <property name="hibernate.format_sql">true</property>
        
        <mapping resource="com/hibernate/bean/Student.hbm.xml"></mapping>
        
        
   </session-factory>
</hibernate-configuration>

 

 

会话工厂类SessionFactory

会话工厂是生成Session的工厂,保存了当前数据库中所有的映射关系,可能只有一个可选的二级缓存,线程安全。它是一个重量级对象,消耗大量系统资源

生成SessionFactory

Configuration cfg=new Configuration().configure();
SessionFactory sessionFactory=cfg.bulidSessionFactory();

可以将生成的SessionFactory对象封装起来,后面使用的时候直接使用getter方法调用,减少系统资源的损耗。

 

Session会话类

这个Session不是JSP中的Session内置对象了,它是会话类,由SessionFactory创建。是数据库持久化操作的核心,负责hibernate的所有持久化操作,通过它执行数据库增删改查等操作。会话类不是线程安全,不要多会话共享一个Session。

创建session

Session session=sessionFactory.openSession();

获取会话中的Session

private final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
Session session=(Session) threadLocal.get();

所以获取Session的方法

public  Session getSession() throws HibernateException{
   Session session=(Session)threadLocal.get();
   if(session==null||!session.isOpen()){
       session=(sessionFactory!=null)?sessionFactory.openSession():null;
       threadLocal.set(session);
   }
   return session;
}