標籤:
一 簡介
1.什麼是ORM
Object/Relation Mapping,即對象/關係映射。可以將其理解為一種規範,具體的ORM架構可以作為應用程式和資料庫的橋樑。物件導向程式設計語言與關聯式資料庫發展不同步時,需要一種中間解決方案,而ORM就是這樣的解決方案 。ORM工具的唯一作用就是:把對持久化對象的儲存、刪除、修改等操作,轉換成對資料庫的操作。
ORM並不是一種具體的產品,而是一類架構的總稱,它概述了這類架構的基本特徵:完成物件導向的程式設計語言到關聯式資料庫的映射。
基於ORM架構完成映射後,既可以利用物件導向程式設計語言的簡單易用性,又可以利用關聯式資料庫的技術優勢。
目前ORM的產品非常多,如Apache組織的QIB,Oracle的TopLink,JDO,JPA等等。
2.Hibernate
Hibernate是目前最流行的ORM架構之一,它是一個面向Java環境的對象/關聯式資料庫映射工具
它也是一個輕量級的O/R Mapping架構,是目前最流行的持久層解決方案,較之另一個持久層架構MyBATIS,更具有物件導向的特徵
Hibernate是ORM規範的實現架構,所有的ORM架構的作用:負責把物件導向的持久化操作,轉化為資料庫標準SQL語句去執行
但是Hibernate不一定能提高程式的效能,可擴充性和可維護性
ORM規範映射思想:一個表映射成一個類;一行記錄(一條資料)映射成一個對象,一列(一個欄位)映射成對象的屬性
3.下載:www.hibernate.org/downloads
解壓後的文檔結構如下:
documentation:各種相關的文檔,包括Hibernate的參考文檔和API文檔等等
lib:存放了核心類庫以及編譯和運行所依賴的第三方類庫。其中lib路徑下的required子目錄下儲存了運行Hibernate的核心類庫,以及必需的第三方類庫
project:存放了Hibernate各種相關項目的原始碼
lgpl.txt、logo等雜項檔案
二 具體實現
1.PO(持久化對象)
Person.class
public class Person {
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", password=" + password
+ ", birthday=" + birthday + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
private Integer id;
private String name;
private int password;
private Date birthday;
public Person() {
super();
}
public Person(String name, int password, Date birthday) {
super();
this.name = name;
this.password = password;
this.birthday = birthday;
}
}
如上所示,Hibernate採用了POJO(普通的、傳統的Java對象)作為持久化類,這就是Hibernate被稱為低侵入式設計的原因。Hibernate不要求持久化類繼承任何父類,或者實現任何介面,這樣可以保證代碼不被汙染。
注意:持久化設計時持久化類通常建議使用一個持久化標識符(ID),並且建議使用封裝類(基本類型有預設值)。通常要給定一個無參構造器,因為有些操作是反射進行的,屬性通常要提供getter/setter方法,持久化類不能是final類型。持久化類中如果使用了集合類型資料,只能使用介面類型進行聲明(List,Set,Map),如:List list=new ArrayList();
如何將一個POJO轉換為PO呢?也就是說如何將上面的Person類進行持久化呢?Hibernate提供了三種方式:
(1)使用持久化註解(以JPA標準註解為主)
(2)使用JPA提供的xml設定檔,很少使用
(3)使用Hibernate傳統的xml對應檔(*.hbm.xml檔案的形式)
這裡使用第一種和第三種方法作為樣本
a.建立Person.hbm.xml
該檔案是一個持久化對應檔,將Java對象映射到資料庫表。幾乎所有的ORM工具都需要一個資料庫欄位與JavaBean屬性匹配的對應檔,在hibernate中一般命名為*.hbm.xml
<?xml version="1.0"? >
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
//name指定需要持久化的類(包加類名),table指定需要映射的表名
<class name="HibernateTest.Person" table="t_person"> <!-- 類對應到資料庫中的表 -->
<id name="id"> <!-- Person類中的id為class的id,id必須指定,name指定持久化類的持久化標識符名稱,generate指定id建置原則-->
<generator class="native"></generator> <!-- 該id為本地產生 -->
</id>
<property name="name" column="t_name"></property>
<property name="password" length="6"></property>
<property name="birthday"></property>
</class>
</hibernate-mapping>
注意:在xml檔案中,name對應的是java類中的對象,property為其他屬性對應配置,name為持久化類中需要映射的屬性名稱,column指定表的列名(不寫表示預設使用屬性名稱),length指定列儲存資料長度,type指定欄位類型
b.使用持久化註解
將Person.java修改為:
@Entity
@Table(name="t_person")
public class Person {
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", password=" + password
+ ", birthday=" + birthday + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="t_name")
private String name;
@Column(length=6)
private int password;
private Date birthday;
public Person() {
super();
}
public Person(String name, int password, Date birthday) {
super();
this.name = name;
this.password = password;
this.birthday = birthday;
}
}
其中,@Entity註解聲明該類是一個持久化類,@Table指定該類映射的表,@Id指定該類的識別屬性,@GeneratedValue指定主鍵建置原則,@Column用於指定資料庫中對應列的詳細資料。由此可見,PO=POJO+持久化註解
2.Hibernate設定檔
在產生PO檔案後,就要在hibernate.cfg.xml中配置各種資訊。
hibernate的project->etc中有各種模板,將其中的hibernate.cfg.xml複製到項目的src路徑中。在這裡展示一下mySQL資料庫的串連方式:
<hibernate-configuration>
<session-factory>
//配置成資料庫方言模式,更方便資料庫識別
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
//資料庫連接池
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">5000</property>
//根據需要自動建立資料庫表
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
//這個是Person.hbm.xml對應的配置
<mapping resource="HibernateTest\Person.hbm.xml"></mapping>
//這個對應的是持久化註解的PO類的路徑
<mapping class="HibernateTest.Person"></mapping>
</session-factory>
</hibernate-configuration>
注意:各種資料庫的串連方式可以具體在hibernate.properties.template檔案尋找,該檔案都有詳細的定義。其中,mapping根據PO持久化的方式有兩種選擇。
hibernate通過C3P0資料來源來管理資料庫串連,當程式建立資料來源執行個體時,系統會一次性建立多個資料庫連接,並將這些資料庫連接儲存在串連池中。程式訪問資料庫時,直接從串連池中取出一個閒置資料庫連接;訪問結束後,無需關閉資料庫直接將串連還給串連池即可。通過這種方式,可以避免頻繁的擷取資料庫連接、關閉資料庫連接所導致的效能下降。將optional路徑下的C3P0的JAR包匯入項目路徑下。
其中,<property name="hibernate.hbm2ddl.auto">update</property>,update表示程式啟動時沒有就建立表,有就檢查有沒有更新(推薦使用)
3.編寫測試程式test.java
public class test {
public static void main(String[] args) {
//建立Configuration執行個體,並載入設定檔(hibernate.cfg.xml),唯一的作用是建立SessionFactory,一旦建立完成就被丟棄
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=new Person(123,"admin",123456,new java.util.Date());
//將Person對象持久化到資料庫
session.save(p);
//事務提交
tx.commit();
session.close();
//關閉SessionFactory,通常不用手動關閉
factory.close();
}
}
結果:
Hibernate:
create table t_person (
id integer not null auto_increment,
t_name varchar(255),
password integer,
birthday datetime,
primary key (id)
) ENGINE=InnoDB
Hibernate:
insert
into
t_person
(t_name, password, birthday)
values
(?, ?, ?)
同時資料庫中建立了一個表為t_person,欄位分別為id(1),t_name(admin),password(123456),birthday(...)
三 Hibernate的體繫結構
1.SessionFactory
這是Hibernate的關鍵對象,它是單個資料庫映射關係經過編譯後的記憶體鏡像,是安全執行緒的。應用程式從SessionFactory中獲得Session執行個體,它在多個線程間進行共用。通常情況下,整個應用只有唯一的一個會話工廠。但是如果訪問多個資料庫,就需要對每一個資料庫使用一個會話工廠。會話工廠緩衝了產生的SQL語句和hibernate在運行時使用的映射中繼資料。
2.Session
它是應用程式與持久儲存層之間互動操作的一個單線程對象,所有的PO必須在Session管理下才可以進行持久化操作。
生存期很短,底層封裝了JDBC串連,也是Transaction的工廠。
Session有一個必選的一級緩衝,顯式執行flush之前,所有持久化操作都在緩衝中。
3.Transaction
代表一次原子操作,具有資料庫事務的概念。將應用代碼從底層的事務實現中抽象出來,這可能是一個JDBC事務,一個JTA使用者事務或是一個公用對象請求代理結構(CORBA),允許應用通過一組一致的API控制事務邊界。這有助於保持Hibernate應用在不同類型的執行環境或容器中的可移植性。使用Hibernate進行操作(增刪改)必須顯示的調用它,即必須要commit。
整個的邏輯結構為:
商務邏輯層:業務對象(對象、屬性、關聯、繼承)-->Person.java
持久化層: ORM API/ORM 實現-->Person.hbm.xml
JDBC-->hibernate.cfg.xml
資料庫層:關係型資料庫
四 改變持久化對象狀態的方法
1.持久化實體
包括save()和persist()兩種方法,如:
Person p=new Person();
p.setName("lyy");
session.save(p);
save()與persist()方法的區別:使用save()方法時會返回該持久化對象的識別屬性值,即主索引值;使用persist()方法時,不會返回任何值。程式執行save()方法會立即將持久化對應的資料插入到資料庫,而persist()方法則保證當它在一個事務外部被調用時,並不立即轉換成insert語句,在需要封裝一個長會話時,這個方法尤為重要。
2.根據主鍵載入持久化類
主要包括load()和get()方法,如:
Person p=session.load(Person.class,1);
load()和get()的區別:主要區別在於是否消極式載入。load()方法具有消極式載入功能,Load()不會立即訪問資料庫,當試圖載入的記錄不存在時,可能返回一個未初始化的代理對象;而get()方法總是立即訪問資料庫,當記錄不存在時,直接返回null
3.更新持久化實體
Person p=session.load(Person.class,1);
p.setPassword("345345");
也就是說,使用load()方法後就可以直接對實體進行更新。
4.使用saveOrUpdate()
saveOrUpdate()表示新增或更新,若id存在就是更新,不存在就報更新失敗;如果不給id,就是新增
public class test {
private static void testSaveOrUpdate(){
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=new Person();
p.setId(3);
p.setPassword(12344);
session.saveOrUpdate(p);
tx.commit();
session.close();
}
public static void main(String[] args) {
testSaveOrUpdate();
}
}
修改成功後,密碼為12344,其他為空白
5.使用merge()
public class test {
private static void merge(){
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=(Person)session.get(Person.class, 3);
p.setName("lyy");
Person p2=(Person)session.merge(p);
p2.setBirthday(new java.util.Date());
tx.commit();
session.close();
}
public static void main(String[] args) {
merge();
}
}
註:持久化狀態物件會在session關閉的時候如果記憶體資料和表資料不一致,將自動同步到資料庫表
或者:
private static void testSaveOrUpdate(){
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=new Person();
p.setId(3);
p.setName("kui");
session.merge(p);
tx.commit();
session.close();
}
結果:name為kui,其他為空白,相當於update
6.刪除有兩種方法:
刪除持久化狀態物件:
public class test {
public static void main(String[] args) {
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=(Person)session.load(Person.class,3);
session.delete(p);
tx.commit();
session.close();
}
}
刪除臨時化狀態物件:
public static void main(String[] args) {
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Person p=new Person();
p.setId(4);
session.delete(p);
tx.commit();
session.close();
}
使用junit進行測試:
在項目中new->Junit Test Case->選中setUp()和tearDown()方法,即初始化和最後的資源釋放
public class myTest {
SessionFactory factory=null;
Session session=null;
Transaction tx=null;
@Before
public void setUp() throws Exception {
System.out.println("---初始化資料---");
Configuration config=new Configuration().configure();
factory=config.buildSessionFactory();
session=factory.openSession();
tx=session.beginTransaction();
}
@After
public void tearDown() throws Exception {
System.out.println("---釋放資源---");
if(session.isOpen()){
session.close();
}
}
@Test
public void test() {
Person p=new Person(2,"admin",123,new Date());
session.persist(p);
tx.commit();
}
}
run as junit test->查看結果
Hibernate入門