1. 程式人生 > >Hibernate核心類和介面詳細介紹

Hibernate核心類和介面詳細介紹

一、hiobernate核心類和介面預覽圖


二、hibernate.properties

這個檔案是以前老版本使用的 類似於hibernate.cfg.xml檔案;作用和hibernate.cfg.xml一致.

三、hibernate.cfg.xml 

(1)詳細介紹

①該檔案主要用於指定各個引數,是hibernate核心檔案
②預設放在src目錄下,也可以放在別的目錄下。
③指定連線資料庫的驅動、使用者名稱、密碼、url、連線池..
④指定物件關係對映檔案的位置.
⑤也可使用hibernate.properties檔案來替代該檔案.(推薦使用hibernate.cfg.xml)。

(2)配置檔案模板

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- hibernate的核心配置檔案 -->
<hibernate-configuration>	
	<session-factory>
		<!--配置使用的driver  -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.username">root</property>
		<property name="connection.password">xu827928</property>
		<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hbmtest</property>
		<!-- 配置dialect方言,明確告訴hibernate連線的是哪種資料庫 -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 顯示出對應sql語句 -->
		<property name="show_sql">true</property>
		<!-- 格式化輸出sql語句 -->
		<property name="format_sql">true</property>		
		
		<!--讓hibernate幫我們建立 一張表 -->
		<!-- 
			update:如果沒有表則建立表 如果有表 則看錶結構是否變化 如果有變化則會建立新表
			如果沒有則新增
			create:每次都建立新的資料庫
		 -->
		<!-- <property name="hbm2ddl.auto">create</property> -->
		<property name="hbm2ddl.auto">update</property>
				
		<!-- 指定管理物件對映檔案 -->
		<mapping resource="com/lc/domain/Employee.hbm.xml"></mapping>
	</session-factory>

</hibernate-configuration>

四、*.hbm.xml

(1)物件關係對映檔案(*.hbm.xml)

  ①該檔案主要作用是建立表和類的對映關係,是不可或缺的重要檔案.
 ②一般放在其對映的類同一個目錄下,但不是必須的。
 ③命名方式一般是 類名.hbm.xml,但不是必須的。

④示意圖:


(2)配置檔案模板

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        '-//Hibernate/Hibernate Mapping DTD 3.0//EN'
        'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>

<!-- 這是對映Employee表的hibernate -->
<!-- 該檔案用於配置domain物件和表的對映關係 -->
<hibernate-mapping package="com.lc.domain">
	<class name="Employee" table="employee">
		<!-- id元素用於指定主鍵屬性 -->		
		<id name="id" column="id" type="java.lang.Integer">
			<generator class="increment" /> 		
		</id>
		<!-- 對其他屬性的配置 -->
		<property name="name" type="java.lang.String">
			<column name="name" not-null="false" />
		</property>
		<property name="email" type="java.lang.String">
			<column name="email" not-null="false" />
		</property>
		<property name="hiredate" type="java.util.Date">
			<column name="hiredate" not-null="false" />
		</property>
	</class>
</hibernate-mapping>

五、Configuration類

(1)詳細介紹

①負責管理hibernate的配置資訊
②讀取hibernate.cfg.xml
③載入hibernate.cfg.xml配置檔案中配置的驅動,url,使用者名稱,密碼,連線池.
④管理 *.hbm.xml物件關係檔案.

(2)示意程式碼:

Configuration cf=new Configuration().configure();

六、SessionFactory(會話工廠)介面

(1)詳細介紹

①快取sql語句和某些資料

②在應用程式初始化的時候建立,是一個重量級的類(吃記憶體),一般用單例模式保證一個應用中只需要一個 SessionFactory例項.

③如果某個應用訪問多個數據庫,則要建立多個會話工廠例項,一般是一個數據庫一個會話工廠例項.
④通過SessionFactory介面可以獲得Session(會話)例項.

(2)示意程式碼:

 Configuration cf=new Configuration().configure();
  SessionFactory sf=cf.buildSessionFactory();
  Session s=sf.getCurrentSession();
  //或者是: Session s=sf.openSession();

七、Session(會話)介面

(1)介面介紹

 ①Session一個例項代表與資料庫的一次操作(當然一次操作可以是crud組合)

 ②Session例項通過SessionFactory獲取,用完需要關閉。
 ③Session是執行緒不同步的(不安全),因此要保證在同一執行緒中使用,可以用getCurrentSessiong()。
 ④Session可以看做是持久化管理器,它是與持久化操作相關的介面

(2)示意程式碼:

	Configuration cf=new Configuration().configure();
	SessionFactory sf=cf.buildSessionFactory();
	Session s=sf.getCurrentSession();
	//或者是: Session s=sf.openSession();

(3)Session(會話)介面的幾個重要方法

Session一般以物件的形式來操作,這裡
給大家演示一下吧!(請參考文件)
①儲存一個物件(記錄)—save方法
②刪除一個物件(記錄)—delete方法
③查詢一個物件(記錄)—get/load方法
④修改一個物件(記錄)—update方法

(4)get()和load()區別

1、get()方法直接返回實體類,如果查不到資料則返回null。load()會
返回一個實體代理物件(當前這個物件可以自動轉化為實體物件),
但當代理物件被呼叫時,如果沒有資料不存在,就會丟擲個
org.hibernate.ObjectNotFoundException異常


2.load先到快取(session快取/二級快取)中去查,如果沒有則返回一個
代理物件(不馬上到DB中去找),等後面使用這個代理物件操作的時
候,才到DB中查詢,這就是我們常說的 load在預設情況下支援延遲加
載(lazy)


3. get先到快取(session快取/二級快取)中去查,如果沒有就到DB中去
查(即馬上發出sql)。總之,如果你確定DB中有這個物件就用
load(),不確定就用get()(這樣效率高)

load VS get

1. 如果查詢不到資料,get 會返回 null,但是不會報錯, load 如果查詢不到資料,則報錯ObjectNotFoundException

2. 使用get 去查詢資料,(先到一級/二級)會立即向db發出查詢請求(select ...), 如果你使用的是 load查詢資料,(先到一級、二級))即使查詢到物件,返回的是一個代理物件,如果後面沒有使用查詢結果,它不會真的向資料庫發select ,當程式設計師使用查詢結果的時候才真的發出select ,這個現象我們稱為懶載入(lazy)

3. 通過修改配置檔案(*.hbm.xml檔案),我們可以取消懶載入

<class  name="Employee" lazy="false" table="employee">

4. 如何選擇使用哪個如果你確定DB中有這個物件就用load(),不確定就用get()(這樣效率高)

(5)openSession()和 getCurrentSession()區別

①採用getCurrentSession()建立的session會繫結到當前執行緒中,而採用openSession()建立的session則不會

②採用getCurrentSession()建立的session在commit或rollback時會自動關閉,而採用openSession()建立的session必須手動關閉.
③使用getCurrentSession()需要在hibernate.cfg.xml檔案中加入

如下配置:
* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全域性事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property> 

(6) openSession()和 getCurrentSession()聯絡

深入探討:
在 SessionFactory啟動的時候,Hibernate 會根據配置建立相應的 CurrentSessionContext,在getCurrentSession()被呼叫的時候,實際被執行的方法是 CurrentSessionContext.currentSession()。

在currentSession()執行時,如果當前Session為空,currentSession會呼叫SessionFactory的openSession。

(7)openSession()和 getCurrentSession()究竟選誰?

原則:
①如果需要在同一執行緒中,保證使用同一個Session則,使用getCurrentSession()
②如果在一個執行緒中,需要使用不同的Session,則使用opentSession()

(8)openSession()和 getCurrentSession()聯絡,用ThreadLocal模式 (執行緒區域性變數模式) 管理Session,程式碼如下:

public class HibernateUtil {
	public static final ThreadLocal session =new ThreadLocal();
	public static final SessionFactory sessionFactory;
   static {
      try {
        sessionFactory = new Configuration().configure().buildSessionFactory();
      } catch (Throwable ex) {
           throw new ExceptionInInitializerError(ex);
      }     
	}
  public static Session currentSession() throws HibernateException {
        Session s = session.get();
        if(s == null) {
          s = sessionFactory.openSession();session.set(s);}
         return s;} 
    public static void closeSession() throws HibernateException {
           Session s = session.get();
        if(s != null) { s.close();}
        session.set(null); }}


八、Transaction(事務)介面

(1)這裡我們簡單給大家說明一下什麼是事務。

事務簡單的說,就是一組對資料庫的操作集合,它們要麼全部成功,要麼全部失敗.這個可以保證資料的一致性,事務具有原子性。
①Transaction是底層的事物實現中抽象出來的介面
②可能是一個jdbc或者jta的事務,這樣有利於hibernate在不同執行環境的移植。
③hibernate要求顯示的呼叫事務(如果僅僅是查詢可以不呼叫.)

Transaction ts=s.beginTransaction();
...
ts.commit();s.close(); 發生異常需要ts.rollback()回滾.

(2)全域性事務和本地事務

本地事務:針對一個數據庫的事務;(jabc事務) 全部事務:跨資料庫的事務(jta事務); 如果要使用getCurrentSession的時候就需要在hibernate.cfg.xml檔案中根據實際配置 * 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全域性事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property> 

九、Query介面

(1)Query介面型別的物件可以對資料庫操作,它可以使用Hql,Qbc,Qbe和原生SQL(native Sql)對資料庫操作.官方推薦使用Hql語句。

十、 Criteria介面

Criteria介面也可用於面向物件方式的查詢,關於它的具體用法我們
這裡先不做介紹,簡單看幾個案例.
最簡單案例:返回50條記錄

Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();
限制結果集內容
List cats = sess.createCriteria(Cat.class)
  .add( Restrictions.like("name", "Fritz%") )
  .add( Restrictions.between("weight", minWeight, maxWeight) )
  .list();

注:轉載請註明出處!!