• 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;
    }
  • 相关阅读:
    使用select和shutdown
    SMTP协议初探(二)linux下c编程实现发邮件
    ortp使用详解 ortprelease.pdf
    网易校园招聘c++题目如何让new操作符不分配内存,只调用构造函数
    虚拟地址空间,堆栈,堆,数据段,代码段
    关于double的输入输出
    CodeForces1238DABstring CodeForces思维+字符串反向思考
    CodeForces1234CPipesdfs
    CodeForces1221A2048 Game思维题
    排序
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5358335.html
Copyright © 2020-2023  润新知