Hibernate4實戰 之 第一部分 Hibernate入門

來源:互聯網
上載者:User
第一部分:Hibernate入門Hibernate是什麼     Hibernate是一個輕量級的ORMapping架構     ORMapping原理(Object Relational Mapping)    ORMapping基本對應規則: 1:類跟表相對應 2:類的屬性跟表的欄位相對應 3:類的執行個體與表中具體的一條記錄相對應 4:一個類可以對應多個表,一個表也可以對應對個類 5:DB中的表可以沒有主鍵,但是Object中必須設定主鍵欄位 6:DB中表與表之間的關係(如:外鍵)映射成為Object之間的關係  7:Object中屬性的個數和名稱可以和表中定義的欄位個數和名稱不一樣   ORMapping的基本實現方式: 使用JDBC,用SQL來操作資料庫,只是看動態產生還是人工寫代碼來實現。 大家想想,我們實現過ORMapping嗎?       Hibernate能幹什麼:     Hibernate主要用來實現Java對象和表之間的映射,除此之外還提供還提供資料查詢和擷取資料的方法,可以大幅度減少開發時人工使用SQL和JDBC處理資料的時間。Hibernate的目標是對於開發人員通常的資料持久化相關的編程任務,解放其中的95%。對於以資料為中心的程式來說,它們往往只在資料庫中使用預存程序來實現商業邏輯,Hibernate可能不是最好的解決方案;對於那些在基於Java的中介層應用中,它們實現物件導向的業務模型和商業邏輯的應用,Hibernate是最有用的。    Hibernate可以協助你消除或者封裝那些針對特定廠商的SQL代碼,並且幫你把結果集從表格式的表示形式轉換到一系列的對象去。  一個非常簡要的Hibernate體繫結構的高層概要圖 Hibernate運行時體繫結構 “最小”的體繫結構方案,要求應用程式提供自己的 JDBC 串連並管理自己的事務。這種方案使用了Hibernate API 的最小子集.     “全面解決”的體繫結構方案,將應用程式層從底層的JDBC/JTA API中抽象出來,而讓Hibernate來處理這些細節。   SessionFactory (org.hibernate.SessionFactory) 針對單個資料庫映射關係經過編譯後的記憶體鏡像,是安全執行緒的(不可變)。 它是產生Session的工廠,本身要用到ConnectionProvider。 Session (org.hibernate.Session) 表示應用程式與持久儲存層之間互動操作的一個單線程對象,此物件存留期很短,隱藏了JDBC串連,也是Transaction的工廠。 Transaction (org.hibernate.Transaction) 應用程式用來指定原子操作單元範圍的對象,它是單線程的,生命週期很短。它通過抽象將應用從底層具體的JDBC、JTA以及CORBA事務隔離開。 ConnectionProvider (org.hibernate.connection.ConnectionProvider)產生JDBC串連的工廠(有串連池的作用)。它通過抽象將應用從底層的Datasource或DriverManager隔離開。僅供開發人員擴充/實現用,並不暴露給應用程式使用。TransactionFactory (org.hibernate.TransactionFactory)產生Transaction對象執行個體的工廠。僅供開發人員擴充/實現用,並不暴露給應用程式使用。  

HelloWorld 要研究怎麼做,先得搞清楚需要做什麼 根據剛才的學習,做基本的Hibernate應用程式,要完成下面的工作:Object、資料庫的表、兩種設定檔、用戶端程式來調用Hibernate的介面進行操作。構建環境 最簡單的方法:把hibernate-release-4.0.0.Beta4.zip包裡面lib/required下的jar包全部添加到工程的library裡面,另外還需添加slf4j的實現包slf4j-log4j12-1.5.8.jar和log4j的實現包log4j-1.2.16.jar,還有別忘了把JDBC的驅動jar包也加入到library裡面Object怎麼做 1:就是前面學過的vo的寫法(規則同樣是那四點) 2:要求必須有一個public為空白參的構造方法,現在寫vo一般不寫構造方法,預設就有一個,但是寫構造方法的時候要注意寫上一個public為空白參的構造方法3:要求提供一個識別屬性(identifier) 4:使用非final的類(因為要使用代理來延遲實體的裝載) 5:設若構建一個對象:cn.javass.h4.hello.UserModel,有四個屬性:uuid,userId,name,age   在資料庫中建表 設若構建一個表為tbl_user,欄位:uuid,userId,name,age 配置xxx.cfg.xml 1:預設名稱為 hibernate.cfg.xml 2:存放在當前classes的根目錄下,開發的時候在src根下就可以了 3:主要有如下四部分配置 : (1)與DB的串連 (2)可選配置 (3)資源檔註冊 (4)二級緩衝 4:配置的時候可以到Hibernate發行包裡面找個hibernate.cfg.xml的例子,比如可以用“\project\hibernate-documentation\quickstart\tutorials\basic\src\test\resources”下面的hibernate.cfg.xml作例子5:樣本如下: java代碼:

查看複製到剪貼簿列印
  1. <?xml version='1.0' encoding='utf-8'?>   
  2. <!DOCTYPE hibernate-configuration PUBLIC   
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">   
  5. <hibernate-configuration>   
  6.     <session-factory>   
  7.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>   
  8.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
      
  9.         <property name="connection.username">test</property>   
  10.         <property name="connection.password">test</property>   
  11.   
  12.         <property name="connection.pool_size">2</property>   
  13.         <property name="dialect">org.hibernate.dialect.OracleDialect</property>   
  14.         <property name="show_sql">true</property>   
  15.   
  16.         <mapping resource="cn/javass/h4/hello/UserModel.hbm.xml"/>   
  17.     </session-factory>   
  18. </hibernate-configuration>  
<?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-configuration>    <session-factory>        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>        <property name="connection.username">test</property>        <property name="connection.password">test</property>        <property name="connection.pool_size">2</property>        <property name="dialect">org.hibernate.dialect.OracleDialect</property>        <property name="show_sql">true</property>        <mapping resource="cn/javass/h4/hello/UserModel.hbm.xml"/>    </session-factory></hibernate-configuration>
配置xxx.hbm.xml 1:與被描述的類同名 ,如:UserModel.hbm.xml 2:存放位置與所描述類存放在同一檔案夾下 3:主要有如下四部分配置 : (1)類和表的映射 (2)主鍵的映射 (3)類的屬性和DB中欄位的映射 (4)關係的映射 4:配置的時候可以到hibernate發行包裡面找個例子,比如可以用“\project\hibernate-core\src\test\java\org\hibernate\test\cid”下面的Customer.hbm.xml作例子5:樣本如下:   java代碼:

查看複製到剪貼簿列印
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.         '-//Hibernate/Hibernate Mapping DTD 3.0//EN'  
  4.         'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>   
  5. <hibernate-mapping>   
  6.     <class name="cn.javass.h4.hello.UserModel" table="tbl_user">   
  7.         <id name="uuid">   
  8.             <generator class="assigned"/>   
  9.         </id>   
  10.         <property name=“userId”></property>   
  11.         <property name=“name”></property>   
  12.         <property name="age"></property>   
  13.     </class>   
  14. </hibernate-mapping>  
<?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'><hibernate-mapping>    <class name="cn.javass.h4.hello.UserModel" table="tbl_user">        <id name="uuid">            <generator class="assigned"/>        </id>        <property name=“userId”></property><property name=“name”></property><property name="age"></property>    </class></hibernate-mapping>
用戶端檔案: java代碼:

查看複製到剪貼簿列印
  1. package cn.javass.h4.hello;   
  2.   
  3. import org.hibernate.Session;   
  4. import org.hibernate.SessionFactory;   
  5. import org.hibernate.Transaction;   
  6. import org.hibernate.cfg.Configuration;   
  7.   
  8. public class Client {   
  9.     public static void main(String[] args) {   
  10.         SessionFactory sf = new Configuration().configure().buildSessionFactory();   
  11.         Session s = null;   
  12.         Transaction t = null;   
  13.   
  14.         try{   
  15.             //準備資料   
  16.             UserModel um = new UserModel();   
  17.             um.setUuid("1");   
  18.             um.setUserId("id1");   
  19.             um.setName("name1");   
  20.             um.setAge(1);   
  21.             s = sf.openSession();   
  22.             t = s.beginTransaction();   
  23.             s.save(um);   
  24.             t.commit();   
  25.        }catch(Exception err){   
  26.             t.rollback();   
  27.             err.printStackTrace();   
  28.       }finally{   
  29.             s.close();   
  30.       }   
  31.     }   
  32. }  
package cn.javass.h4.hello;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class Client {    public static void main(String[] args) {        SessionFactory sf = new Configuration().configure().buildSessionFactory();        Session s = null;        Transaction t = null;        try{            //準備資料            UserModel um = new UserModel();            um.setUuid("1");            um.setUserId("id1");            um.setName("name1");            um.setAge(1);            s = sf.openSession();            t = s.beginTransaction();            s.save(um);            t.commit();       }catch(Exception err){            t.rollback();            err.printStackTrace();      }finally{            s.close();      }    }}

 

測試:直接在Elipse裡面運行Client檔案即可,運行結束,你將會看到在console輸出:“Hibernate: insert into tbl_user (userId, name, age, uuid) values (?, ?, ?, ?)”,開啟資料庫的資料表,你會看到一條值已經加入了。  說明: 1:SessionFactory sf = new Configuration().configure().buildSessionFactory();這句話的意思是讀取hibernate.cfg.xml,建立Session工廠,是安全執行緒的。預設是”hibernate.cfg.xml”,不用寫出來,如果檔案名稱不是”hibernate.cfg.xml”,那麼需要顯示指定,如下: SessionFactory sf = new Configuration(). configure( “javass.cfg.xml” ).buildSessionFactory();2:Session是應用程式主要使用的Hibernate介面,約相當於JDBC的Connection+Statement/PreparedStatement的功能,是線程不安全的  3:在Hibernate4裡面,已經不推薦使用Configuration類了,而改為使用 ServiceRegistryBuilder和MetadataSources來代替,新的寫法大致如下:ServiceRegistryBuilder builder = new ServiceRegistryBuilder().configure(); builder.applySetting("connection.driver_class", "oracle.jdbc.driver.OracleDriver");builder.applySetting("connection.url", "jdbc:oracle:thin:@localhost:1521:orcl");builder.applySetting("connection.username", "ztb"); builder.applySetting("connection.password", "ztb"); builder.applySetting("connection.pool_size", "2"); builder.applySetting("hibernate.dialect", "org.hibernate.dialect.OracleDialect");builder.applySetting("show_sql", "true");   MetadataSources sources = new MetadataSources( builder.buildServiceRegistry() );sources.addResource("cn/javass/h4/hello/UserModel.hbm.xml");   MetadataImpl metadata = (MetadataImpl) sources.buildMetadata(); SessionFactory sf = metadata.getSessionFactoryBuilder().buildSessionFactory();這種寫法,現在還沒有實現完全,不太好用,所以官方給出的樣本裡面還是採用以前的方式,大家先瞭解一下。 4:這裡使用的事務Transaction是Hibernate的Transaction,需要有,不能去掉。   為什麼必須有這個Hibernate的事務呢?以HelloWorld為例來看看:   視頻配套PPT,視頻地址【
Hibernate4實戰-獨家視頻課程】 原創內容 轉自請註明【
http://sishuok.com/forum/blogPost/list/2461.html】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.