1. 程式人生 > >3. Hibernate基本配置及操作

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()

      在這裡插入圖片描述