zoukankan      html  css  js  c++  java
  • hibernate中3个重要的类 Configuration SessionFactory Session

    配置类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;
    }
  • 相关阅读:
    设计模式学习总结系列应用实例
    【研究课题】高校特殊学生的发现及培养机制研究
    Linux下Oracle11G RAC报错:在安装oracle软件时报file not found一例
    python pro practice
    openstack python sdk list tenants get token get servers
    openstack api
    python
    git for windows
    openstack api users list get token get servers
    linux 流量监控
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5358335.html
Copyright © 2011-2022 走看看