上篇大概的介紹了Hibernate框架,本篇一個簡單的hibernate例子來學習。
### Hibernate配置
(1)??創建自己的java項目。
(2)??向自己的項目中添加Hibernate的相關的jar,我們可以創建自己的UserLibrary,這樣就直接加入這個依賴包就可以了(如圖2.1圖2.2)。

圖2.1

圖2.2
需要添加上的jar包包括,a、加入hibernate-3.2/lib/*.jar?b、加入hibernate-3.2/hibernate2.jar?c、加入數據庫驅動(mysql驅動可以去官網上下載)這樣添加到我們自定義的依賴包中,再在程序中引入這個包就可以了。
(3)加入hibernate配置文件,在學struts的時候我們常用的配置文件是struts-config.xml,hibernate的配置文件hibernate.cfg.xml,我們可以在hibernate-3.2\etc\hibernate.cfg.xml目錄下拷貝到我們項目中的src下。
這樣以上步驟就完成了幾本hibernate的基本配置。
(4)接下來我們要建立我們的實體類了,以便完成對象與表的映射。建立User實體類,完成實體類的映射User.hbm.xml。代碼如下所示。
User類代碼:
~~~
package com.bjpowernode.hibernate;
import java.util.Date;
//user實體。
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;
}
}
~~~
User.hbm.xml代碼如下所示:
~~~
<?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 package="org.hibernate.auction">
<class name="com.bjpowernode.hibernate.User" >
<id name="id">
<generator class="uuid" />
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
~~~
(5)??將User.hbm.xml文件加入到hibernate.cfg.xml文件中,代碼如下所示。
~~~
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="foo">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Hibernate_first</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!--<property name="hibernate.format_sql">true</property> -->
<mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
~~~
(6)??編寫工具類,ExportDB.java生成數據庫中的表,代碼如下所示。
~~~
package com.bjpowernode.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 將hbm生成ddl.
* @author summer
*
*/
public class ExportDB {
/**將hbm生成ddl.
* @param args
*/
public static void main(String[] args) {
//使用hibernate相關類configuation.
//默認讀取hibernate.cfg.xml文件.
Configuration cfg = new Configuration().configure();
//接受配置文件.
SchemaExport export = new SchemaExport(cfg);
//打印到控制臺,輸出到數據庫.
export.create(true, true);
}
}
~~~
(7)??建立客戶端類Client,向表User中添加數據。代碼如下所示。
? ??
~~~
package com.bjpowernode.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 客戶端向表中添加數據.
* @author summer
*
*/
public class client {
public static void main(String[] args) {
//默認讀取的是hibernate.cfg.xml 文件.
Configuration cfg = new Configuration().configure();
//建立SessionFactory.
SessionFactory factroy = cfg.buildSessionFactory();
//取得session.
Session session = null;
try
{
//通過工廠取得session
session = factroy.openSession();
//開啟事務.
session.beginTransaction();
//給對象賦值.
User user = new User();
user.setName("張三");
user.setPassword("123");
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.
//hibernate中已經將connection的的關閉封裝了.
//我們沒有看到任何一條sql語句.
session.close();
}
}
}
}
}
~~~
(8)??加入log4j配置文件,將該配置文件拷貝到我們自己項目的src下,便于調試和跟蹤。
(9)建立自己的數據庫,執行ExportDB.java生成數據庫中的表,執行client.java完成了對象與關系數據庫表的對應,如下圖3.2,建立的User表。
? ??
圖3.2
? ? ? ? ? ? ? ??
### Configuration類
上述代碼中,Configuration類負責管理Hibernate的配置信息,一個Configuration類的實例代表了應用程序中java類到數據庫映射的集合。我們創建一個Configuration實例,并通過這個實例創建SessionFactory實例。???//默認讀取的是hibernate.cfg.xml文件.
??????????Configurationcfg = new Configuration().configure();
??????????
??????????//建立SessionFactory.
??????????SessionFactoryfactroy = cfg.buildSessionFactory();
在這里默認讀取的是hibernate.cfg.xml文件,在新建一個Configuration的實例時,Hibernate會在類路徑中查找hibernate.properties文件和hibernate.cfg.xml文件,如果兩個文件同時存在,則hibernate.cfg.xml將覆蓋hibernate.properties文件。如果兩個文件都不存在則拋出異常。我們也可以指定配置文件的路徑,不用系統默認的hibernate.cfg.xml文件:Stringfilename= “my_hibernate_cfg.xml”?Configuration config = new Configuration().configure(filename);
### Hibernate配置文件
從配置文件中可以看出,這個配置文件描述的是數據庫的信息,如數據庫看的URL、用戶名、密碼,hibernate使用方言(那種數據庫),同時還可以管理數據庫中各個表的映射文件,還可以配置事務策略等。
### SessionFactory類
SessionFactory負責Session實例的創建,為了創建一個SessionFactory對象,必須在Hibernate初始化的時候創建一個Configuration類的實例,并將已經寫好的映射文件交給它處理。這樣Configuration對象就可以創建一個SessionFactory對象,當SessionFactory對象創建成功后,Configuration對象就沒用過了。SessionFactory是線程安全的,可以被多個單線程調用以取得session對象,而構造SessionFactory要消耗資源,所以多數情況下一個應用中只初始化一個SessionFactory,在這里我們可以考慮使用靜態方法,來解決這個問題。在上述代碼的基礎上我們抽取出一個工具類,用來專門實例化工廠管理session,并且采用static每次只初始化一次,代碼如下所示。
~~~
package com.bjpowernode.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory factory;
//static只初始化一次.
static
{
try{
//默認讀取的是hibernate.cfg.xml 文件.
Configuration cfg = new Configuration().configure();
//建立SessionFactory.
factory = cfg.buildSessionFactory();
}catch(Exception e )
{
e.printStackTrace();
}
}
public static Session getSession()
{
//打開session.
return factory.openSession();
}
//關閉session.
public static void closeSession(Session session)
{
//判斷是否為空.
//判斷是否是打開狀態再進行關閉.
if(session!=null)
{
if(session.isOpen())
{
session.close();
}
}
}
//返回工廠類.
public static SessionFactory getSessionFactory()
{
return factory;
}
}
~~~
### Session
Session是Hibernate運作的核心,對象的聲明周期、事務的管理以及數據庫的存取都與它息息相關。Session是由SessionFactory創建的,SessionFactory是線程安全的,而Session不是線程安全的,所以讓多個線程共享一個session,會引起沖突。
下一篇[Hibernate](http://blog.csdn.net/lovesummerforever/article/details/19171571)[持久化對象的三個狀態](http://blog.csdn.net/lovesummerforever/article/details/19171571)。
- 前言
- Struts旅程(一)Struts簡介和原理
- struts旅程(二)Struts登錄示例
- Struts旅程(三)Struts表單處理器ActionForm(靜態動態)
- Struts旅程(四)MVC向struts MVC框架演變過程
- Struts旅程(五)struts控制器DispatchAction
- Struts旅程(六)Struts頁面轉發控制ActionForward和ActionMapping
- Hibernate旅程(一)Hibernate架構概述
- Hibernate旅程(二)Hibernate實例
- Hibernate旅程(三)Hibernate持久化對象的三個狀態
- Hibernate旅程(四)Hibernate對數據庫刪除、查找、更新操作
- Hibernate旅程(五)Hibernate映射--基本類映射和對象關系映射
- Hibernate旅程(六)Hibernate映射--繼承映射
- Hibernate旅程(七)Hibernate緩存機制--一級緩存
- Hibernate旅程(八)Hibernate緩存機制--二級緩存
- Hibernate旅程(九)Hibernate緩存機制--查詢緩存
- Spring旅程(一)為什么使用Spring
- Spring旅程(二)非Spring向Spring過渡-- Spring IOC容器的使用
- Spring旅程(三) AOP--Spring AOP容器基礎
- Spring旅程(四) AOP--Spring AOP實例
- SSH旅程(五)Spring運用到Hibernate中
- SSH旅程(六)Spring和struts結合(方案一)