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包
![](http://static.javashuo.com/static/loading.gif)
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文件,構建依賴包
![](http://static.javashuo.com/static/loading.gif)
三、提供hibernate.cfg.xml文件,完成基本配置
四、寫代碼
(1)創建實體類User.java
[java] view plain copy
- package com.liang.hibernate;
-
- import java.util.Date;
-
- public class User {
- private String id;
- private String name;
- private String password;
- private Date createTime;
- private Date expireTime;
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Date getCreateTime() {
- return createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- public Date getExpireTime() {
- return expireTime;
- }
- public void setExpireTime(Date expireTime) {
- this.expireTime = expireTime;
- }
-
- }
(2)提供User.hbm.xml文件,完成實體類映射
[html] view plain copy
- <span style="font-size:12px;"><?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <!--生成默認爲user的數據庫表-->
- <class name="com.liang.hibernate.User">
- <id name="id">
- <!-- 算法的核心思想是結合機器的網卡、當地時間、一個隨機數來生成GUID -->
- <generator class="uuid"></generator>
- </id>
- <property name="name"></property>
- <property name="password"></property>
- <property name="createTime" type="date"></property>
- <property name="expireTime" type="date"></property>
- </class>
-
- </hibernate-mapping></span>
(3)將User.hbm.xml文件加入到hibernate.cfg.xml文件中
[html] view plain copy
- <!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
- <!-- 設置數據庫URL -->
- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
- <!-- 數據庫用戶名 -->
- <property name="hibernate.connection.username">root</property>
- <!-- 數據庫密碼 -->
- <property name="hibernate.connection.password">123456</property>
- <!-- 指定對應數據庫的方言,hibernate爲了更好適配各類關係數據庫,針對每種數據庫都指定了一個方言dialect -->
- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
-
- <!-- 映射文件 -->
- <mapping resource="com/liang/hibernate/User.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
(4)編寫工具類ExportDB.java,將hbm生成ddl,也就是hbm2ddl
[java] view plain copy
- package com.liang.hibernate;
-
- import org.hibernate.cfg.Configuration;
- import org.hibernate.tool.hbm2ddl.SchemaExport;
-
- /**
- * 將hbm生成ddl
- * @author liang
- *
- */
- public class ExportDB{
- public static void main(String[]args){
- //默認讀取hibernate.cfg.xml文件
- Configuration cfg = new Configuration().configure();
- ////生成並輸出sql到文件(當前目錄)和數據庫
- SchemaExport export = new SchemaExport(cfg);
- export.create(true, true);
- }
- }
測試以前,要提早創建數據庫hibernate_first,測試以下:
控制檯打印的SQL語句:
[sql] view plain copy
- drop table if exists User
- create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime date, expireTime date, primary key (id))
數據庫表結構:
![](http://static.javashuo.com/static/loading.gif)
(5)創建客戶端類Client,添加用戶數據到mySQL
[java] view plain copy
- package com.liang.hibernate;
-
- import java.util.Date;
-
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
-
- public class Client {
- public static void main(String[]args){
- //讀取hibernate.cfg.xml文件
- Configuration cfg = new Configuration().configure();
- //創建SessionFactory
- SessionFactory factory =cfg.buildSessionFactory();
-
- //取得session
- Session session = null;
-
- try{
- //開啓session
- session = factory.openSession();
- //開啓事務
- session.beginTransaction();
-
- User user = new User();
- user.setName("jiuqiyuliang");
- user.setPassword("123456");
- user.setCreateTime(new Date());
- user.setExpireTime(new Date());
- //保存User對象
- session.save(user);
-
- //提交事務
- session.getTransaction().commit();
-
- }catch(Exception e){
- e.printStackTrace();
- //回滾事務
- session.getTransaction().rollback();
- }finally{
- if(session != null){
- if(session.isOpen()){
- //關閉session
- session.close();
- }
- }
- }
- }
- }
右鍵debug運行,測試完成以後,咱們查詢一下測試結果:
![](http://static.javashuo.com/static/loading.gif)
五、爲了在調試過程當中能觀察到Hibernate的日誌輸出,最好加入log4j.properties配置文件、在CLASSPATH中新建log4j.properties配置文件或將該配置文件拷貝到src下,便於程序調試。
內容以下:
[html] view plain copy
- <span style="font-size:12px;">### direct log messages to stdout ###
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.Target=System.out
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
- ### direct messages to file hibernate.log ###
- #log4j.appender.file=org.apache.log4j.FileAppender
- #log4j.appender.file.File=hibernate.log
- #log4j.appender.file.layout=org.apache.log4j.PatternLayout
- #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
- ### set log levels - for more verbose logging change 'info' to 'debug' ###
-
- log4j.rootLogger=warn, stdout</span>
配置完成後,項目結構以下圖所示:
![](http://static.javashuo.com/static/loading.gif)
5、最後
本身動手豐衣足食,實踐出真理,紙上得來終覺淺,絕知此事要躬行。雖然這個實例很是簡單,可是咱們踏進了持久層框架的大門。
從上面的簡單實例能夠看到,咱們只是使用Hibernate對User這一個實體進行了映射,比較簡單,可是徹底不符合實際。如何像關係型數據庫同樣表示多種關聯關係,例如:一對一,一對多,多對多等等,咱們還須要深刻。下篇博文,咱們介紹Hibernate的基本映射原理以及關聯關係映射。