3. Hibernate基本配置及操作

3. Hibernate基本配置及操作

  1. Hibernate核心配置文件

    • hibernate.cfg.xml

      Hibernate中最核心的配置文件

      • 数据库方言的配置
      • 数据库连接参数的配置
      • 数据库连接池的配置
      • 加载对象关系映射文件
      • 其它配置
      <hibernate-configuration>
      	<session-factory>
      		<!--配置mysql数据库连接参数-->
      		<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
      		<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
      		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
      		<property name="connection.username">root</property>
      		<property name="connection.password">123</property>
      		 <!--配置C3P0连接池参数 -->
      		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
      		<property name="hibernate.c3p0.max_size">10</property>
      		<property name="hibernate.c3p0.min_size">5</property>
      		<property name="hibernate.c3p0.timeout">5000</property>
      		<property name="hibernate.c3p0.max_statements">10</property>
      		
      		<property name="hibernate.show_sql">true</property>
      		<property name="hibernate.format_sql">true</property>
      		
      		<mapping resource="learn/hibernate/entity/Student.hbm.xml"/>
      	</session-factory>
      
      </hibernate-configuration>
      

    • 对象关系映射文件(XXX.hbm.xml)

      Hibernate映射主要是通过对象关系映射文件(XXX.hbm.xml)来实现的

      • 对象关系映射文件的作用
      • 映射关系

      Student.java

      public class Student implements Serializable {
          private int id;
          private String name;
          private int age;
          //getter setter
      }
      

      Student.hbm.xml

      hibernate-mapping>
      
          <class name="learn.hibernate.entity.Student" table="stu_tab" >
              <id name="id" column="stu_id">
                  <generator class="native"/>
              </id>
              <property name="name" column="stu_name"/>
              <property name="age" column="stu_age"/>
          </class>
      </hibernate-mapping>
      

      OID生成器:

      在这里插入图片描述

      Hibernate内置的基本映射类型:

      在这里插入图片描述

      Hibernate内置的日期和时间映射类型:

      在这里插入图片描述
      Hibernate内置的大对象映射类型:

      在这里插入图片描述

  2. Session缓存和持久化生命周期

    • Session缓存原理:

      Session缓存:在Hibernate中被称为一级缓存。

      • 当应用程序调用Session的CRUD方法、以及调用查询接口的list()、iterate()或filter()方法时,如果在Session缓存中还不存在相应的对象,Hibernate就会把该对象加入到第一级缓存中
      • 当清理缓存时,Hibernate会根据缓存中对象的状态变化来同步更新数据库
    • Session缓存的作用:

      • 减少访问数据库的频率
      • 保证缓存中的对象与数据库中的数据同步
      • 当缓存中的持久化对象之间存在循环关联关系时,Session会保证不出现访问对象图的死循环,以及由死循环引起的JVM堆栈溢出异常
    • Session缓存的应用

      • 当应用程序调用Transaction的commit()方法时,commit()方法会清理缓存,然后再向数据库提交事务
      • 当应用程序中显示调用session的flush()方法时,通过Session的setFushMode(FlushMode fm)方法来设定清理缓存的时间点。
        • FlushMode.ALWAYS
        • FlushMode.AUTO
        • FlushMode.COMMIT
        • FlushMode.MANUAL
    • 示例

      session.flush();设为手动

      session.setFlushMode(FlushMode.MANUAL);
      Transaction tx=session.beginTransaction();
      try{
      
          Student stu=(Student)session.get(Student.class, 3);
      	stu.setName("new name");
      	tx.commit();
      
      }catch(Exception ce){
      	tx.rollback();
      }finally{
        
      	session.close();
      }
      

      此时sql语句并没有update操作,session并没有和数据库进行同步,此时数据库中数据不会被更新

      Hibernate: 
          insert 
          into
              stu_tab
              (stu_name, stu_age) 
          values
              (?, ?)
      

      增加session.flush();

      session.setFlushMode(FlushMode.MANUAL);
      Transaction tx=session.beginTransaction();
      try{
         Student stu=(Student)session.get(Student.class, 3);
         stu.setName("new name");
         
         session.flush();
         
         tx.commit()}catch(Exception ce){
         tx.rollback();
      }finally{
         session.close();
      }
      
      

      sql语句中出现update,此时会同步session与数据库中的数据!

      Hibernate: 
          select
              student0_.stu_id as stu_id1_0_0_,
              student0_.stu_name as stu_name2_0_0_,
              student0_.stu_age as stu_age3_0_0_ 
          from
              stu_tab student0_ 
          where
              student0_.stu_id=?
      Hibernate: 
          update
              stu_tab 
          set
              stu_name=?,
              stu_age=? 
          where
              stu_id=?
      
    • 持久化对象生命周期

      • 瞬时(Transient)状态

      • 持久化(Persistent)状态

      • 脱管(detached)状态

      • 移除(removed)状态

        在这里插入图片描述

  3. Session基本操作

    Session接口是Hibernate向应用程序提供的操作数据库的最主要的接口,它提供了基本的保存、查询、更新和删除等方法。

    • save()方法

      使一个瞬时状态的对象转变为持久化状态的对象

      在这里插入图片描述

      @Test
      public void add(){
         Configuration cfg = new Configuration().configure();
         SessionFactory factory = cfg.buildSessionFactory();
         Session session = factory.openSession();
         Transaction tx=session.beginTransaction();
         try{
            Student stu=new Student();
            stu.setName("zhangsan");
            stu.setAge(20);
            session.save(stu);
            stu.setAge(30);
            tx.commit();
         }catch(Exception ce){
            tx.rollback();
         }finally{
            session.close();
         }
      }
      
    • get()和load()方法

      都是根据给定的OID,加载一个持久化对象

      异同点:

      • 都是先根据给定OID从缓存(一级,二级)中获取,存在就是直接返回
      • get方法:执行SQL从数据库获取
      • load方法:返回一个代理对象(延迟加载,懒加载)
      • 如果数据库不存在给定OID对应的记录:get方法方法返回null;load方法抛出ObjectNotFoundException异常

      在这里插入图片描述

      @Test
      public void get(){
         Configuration cfg = new Configuration().configure();
         SessionFactory factory = cfg.buildSessionFactory();
         Session session = factory.openSession();
         Transaction tx=session.beginTransaction();
      
         try{
            Student stu=(Student)session.get(Student.class, 1);
            System.out.println(stu.getId()+stu.getName()+stu.getAge());     
            tx.commit();
         }catch(Exception ce){
            tx.rollback();
         }finally{
            session.close();
         }
         
      }
      
      @Test
      public void load(){
         Configuration cfg = new Configuration().configure();
         SessionFactory factory = cfg.buildSessionFactory();
         Session session = factory.openSession();
         Transaction tx=session.beginTransaction();
         Student stu=null;   
         try{
            stu=(Student)session.load(Student.class, 1);
            //System.out.println(stu.getName());//应该在此处使用
            tx.commit();
         }catch(Exception ce){
            tx.rollback();
         }finally{
            session.close();
         }
         
         System.out.println(stu.getName()); //会抛出异常 所以一定要在session关闭前使用
         
      }
      
    • delete()方法

      使一个持久化对象变成移除状态,从数据库中移除它的持久化状态

      在这里插入图片描述

    • update()方法

      使一个脱管对象重附到新的session中,成为持久化对象

      在这里插入图片描述

    • merge()方法

      • 将给定实例的状态复制到具有相同标识符的持久化实例上,并返回这个持久化实例
      • 常用来代替update()、saveOrUpdate()

      在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hi_maxin/article/details/83751809