Hibernate搭建開發環境+簡單實例(二)

 Hibernate是很是典型的持久層框架,持久化的思想是很是值得咱們學習和研究的。這篇博文,咱們主要以實例的形式學習Hibernate,不深究Hibernate的思想和原理,不然,一味追求,苦學思想和原理,到最後可能什麼也學不會,從實踐入手,熟能生巧,思想和原理天然而然領悟。html

 

1、開發環境

 

         Win8 + jdk1.7 + MyEclipse + Tomcat5.0 + MySQLjava

      說明:其實Hibernate是很是獨立的框架,根本不須要MyEclipse,Eclipse,Tomcat,Log4J等,他們只不過是能知足咱們其餘的需求,才把他們引進來的。mysql

 

2、下載文件

 

你須要Java SDK、 Hibernate包、和JDBC Driver。
 
一、Hibernate包下載地址:
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc

二、JDBC Driver根據你的數據庫來定,通常database官網都有。Hibernate支持經常使用的數據庫,好比 MySQL, Oracle等等。這兩個數據庫是如今比較經常使用的,都有JDBC Driver:

Oracle JDBC Driver下載地址(下載前必須贊成Oracle協議書)
http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC Driver下載地址
http://dev.mysql.com/downloads/connector/j/3.0.html
 算法

3、所需jar包

   

hibernate3.jar                                             Hibernate的核心包sql

dom4j-1.6.1.jar                                            dom4j讀取xml文件包數據庫

mysql-connector-java-3.1.13-bin.jar        MySQL的jdbc驅動包apache

       Hibernate的做用:讓咱們以面向對象的方式或思惟來考慮怎麼向關係型數據庫存取數據。它須要與相應的數據庫打交道,因此須要相應的jdbc驅動。咱們的database用的是MySQL,因此須要引入MySQL的jdbc驅動。session

log4j-1.2.11.jar                                           記錄日誌框架oracle

        因爲log4j的記錄日誌比jdk自帶的記錄日誌功能更加美觀,簡單,易配置日誌級別,便於調試,咱們選擇使用log4j。app

 

必需要引入的jar:

 

commons-logging-1.0.4.jar                       抽象的日誌記錄框架

      自己並無實現真正的寫日誌能力(看包結構便可知道)而是結合其它的日誌系統如Log4j或者java自己的java.util.logging做爲日誌輸出組件,來實現日誌記錄的功能。

commons-collections-2.1.1jar                各類集合類和集合工具類的封裝

cglib-2.1.3.jar                                            動態代理,Hibernate用它來實現PO字節碼的動態生成

asm.jar                                                      cglib須要依賴的jar,ASM字節碼庫

 

注:做爲初學者不提倡這種作法,只須要將hibernate所要依賴的第三方jar包都引入便可,不然作其餘實例時會報NoClassDefFoundError的錯誤,解決方案:只需將對應jar引入便可。因爲這是一個簡單實例,僅僅須要引入這些jar。

 

4、代碼展現

 

一、在IDE中建立java項目(比較簡單再也不演示)

 

二、建立source folder,命名爲Hibernate3,在Hibernate下載文件中找到咱們所須要的三個配置文件和全部jar包,拷貝所需jar文件,構建依賴包

 

           

三、提供hibernate.cfg.xml文件,完成基本配置

 

四、寫代碼

 

(1)創建實體類User.java

  

[java] view plain copy

  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.     private String id;  
  7.     private String name;  
  8.     private String password;  
  9.     private Date createTime;  
  10.     private Date expireTime;  
  11.       
  12.     public String getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(String id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getPassword() {  
  25.         return password;  
  26.     }  
  27.     public void setPassword(String password) {  
  28.         this.password = password;  
  29.     }  
  30.     public Date getCreateTime() {  
  31.         return createTime;  
  32.     }  
  33.     public void setCreateTime(Date createTime) {  
  34.         this.createTime = createTime;  
  35.     }  
  36.     public Date getExpireTime() {  
  37.         return expireTime;  
  38.     }  
  39.     public void setExpireTime(Date expireTime) {  
  40.         this.expireTime = expireTime;  
  41.     }  
  42.   
  43. }  

 

 

 

 

 

 

 

 

 

 

 

(2)提供User.hbm.xml文件,完成實體類映射

 

[html] view plain copy

  1. <span style="font-size:12px;"><?xml version="1.0"?>  
  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.     <!--生成默認爲user的數據庫表-->  
  7.     <class name="com.liang.hibernate.User">  
  8.         <id name="id">  
  9.             <!-- 算法的核心思想是結合機器的網卡、當地時間、一個隨機數來生成GUID -->  
  10.             <generator class="uuid"></generator>  
  11.         </id>  
  12.         <property name="name"></property>  
  13.         <property name="password"></property>  
  14.         <property name="createTime" type="date"></property>  
  15.         <property name="expireTime" type="date"></property>  
  16.     </class>  
  17.       
  18. </hibernate-mapping></span>  

 

 

 

 

 

 

 

 

 

 

 

(3)將User.hbm.xml文件加入到hibernate.cfg.xml文件中

 

[html] view plain copy

  1. <!DOCTYPE hibernate-configuration PUBLIC  
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <!-- 設置數據庫驅動 -->  
  8.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  9.         <!-- 設置數據庫URL -->  
  10.         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>  
  11.         <!-- 數據庫用戶名 -->  
  12.         <property name="hibernate.connection.username">root</property>  
  13.         <!-- 數據庫密碼 -->  
  14.         <property name="hibernate.connection.password">123456</property>  
  15.         <!-- 指定對應數據庫的方言,hibernate爲了更好適配各類關係數據庫,針對每種數據庫都指定了一個方言dialect -->  
  16.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  17.           
  18.         <!-- 映射文件 -->  
  19.         <mapping resource="com/liang/hibernate/User.hbm.xml"/>  
  20.     </session-factory>  
  21. </hibernate-configuration>  

 

(4)編寫工具類ExportDB.java,將hbm生成ddl,也就是hbm2ddl

 

[java] view plain copy

  1. package com.liang.hibernate;  
  2.   
  3. import org.hibernate.cfg.Configuration;  
  4. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  5.   
  6. /** 
  7.  * 將hbm生成ddl 
  8.  * @author liang 
  9.  * 
  10.  */  
  11. public class ExportDB{    
  12.     public static void main(String[]args){  
  13.         //默認讀取hibernate.cfg.xml文件  
  14.         Configuration cfg = new Configuration().configure();  
  15.         ////生成並輸出sql到文件(當前目錄)和數據庫  
  16.         SchemaExport export = new SchemaExport(cfg);  
  17.         export.create(true, true);  
  18.     }  
  19. }  

 

測試以前,要提早創建數據庫hibernate_first,測試以下: 

 

控制檯打印的SQL語句:

 

[sql] view plain copy

  1. drop table if exists User  
  2. create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime date, expireTime date, primary key (id))  

 

數據庫表結構:

           

 

(5)創建客戶端類Client,添加用戶數據到mySQL

 

[java] view plain copy

  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.hibernate.cfg.Configuration;  
  8.   
  9. public class Client {  
  10.     public static void main(String[]args){  
  11.         //讀取hibernate.cfg.xml文件  
  12.         Configuration cfg = new Configuration().configure();  
  13.         //創建SessionFactory  
  14.         SessionFactory factory =cfg.buildSessionFactory();  
  15.           
  16.         //取得session  
  17.         Session session = null;  
  18.           
  19.         try{  
  20.             //開啓session  
  21.             session = factory.openSession();  
  22.             //開啓事務  
  23.             session.beginTransaction();  
  24.               
  25.             User user = new User();  
  26.             user.setName("jiuqiyuliang");  
  27.             user.setPassword("123456");  
  28.             user.setCreateTime(new Date());  
  29.             user.setExpireTime(new Date());  
  30.             //保存User對象  
  31.             session.save(user);  
  32.               
  33.             //提交事務  
  34.             session.getTransaction().commit();  
  35.               
  36.         }catch(Exception e){  
  37.             e.printStackTrace();  
  38.             //回滾事務  
  39.             session.getTransaction().rollback();  
  40.         }finally{  
  41.             if(session != null){  
  42.                 if(session.isOpen()){  
  43.                     //關閉session  
  44.                     session.close();  
  45.                 }  
  46.             }  
  47.         }  
  48.     }  
  49. }  


右鍵debug運行,測試完成以後,咱們查詢一下測試結果:

            

 

五、爲了在調試過程當中能觀察到Hibernate的日誌輸出,最好加入log4j.properties配置文件、在CLASSPATH中新建log4j.properties配置文件或將該配置文件拷貝到src下,便於程序調試。

內容以下:

 

[html] view plain copy

  1. <span style="font-size:12px;">### direct log messages to stdout ###  
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.stdout.Target=System.out  
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  6.   
  7. ### direct messages to file hibernate.log ###  
  8. #log4j.appender.file=org.apache.log4j.FileAppender  
  9. #log4j.appender.file.File=hibernate.log  
  10. #log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  11. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  12.   
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###  
  14.   
  15. log4j.rootLogger=warn, stdout</span>  

 

配置完成後,項目結構以下圖所示:

 

          


 

5、最後

 

      本身動手豐衣足食,實踐出真理,紙上得來終覺淺,絕知此事要躬行。雖然這個實例很是簡單,可是咱們踏進了持久層框架的大門。

 

      從上面的簡單實例能夠看到,咱們只是使用Hibernate對User這一個實體進行了映射,比較簡單,可是徹底不符合實際。如何像關係型數據庫同樣表示多種關聯關係,例如:一對一,一對多,多對多等等,咱們還須要深刻。下篇博文,咱們介紹Hibernate的基本映射原理以及關聯關係映射。

相關文章
相關標籤/搜索