【SSH之旅】一步步學習Hibernate框架(一):關於持久化
在不引用不論什麽框架下,我們會通過平庸的代碼不停的對數據庫進行操作,產生了非常多冗余的可是又有規律的底層代碼,這樣頻繁的操作數據庫和大量的底層代碼的反復書寫極大的浪費了程序人員的書寫。就在這樣一種情況下,Hibernate框架應運而生了。
事實上Hibernate封裝的就是Model模型中的model,封裝的這部分又叫持久層。在這層中對對象進行加入、刪除、更新、查詢等操作就叫做持久化。
持久化的對象有三種狀態:Transient Objects、Persist Objects、Detached Objects。
Transient Objects:
使用new操作初始化的對象不會被立馬持久化。其狀態時瞬時的,不被Session管理,此時,也沒有不論什麽跟數據庫相關聯的行為,即數據庫中沒有這個記錄,僅僅要不被其它對象引用,他們的狀態將會丟失,並由垃圾回收機制回收。
在下面情況下對象處於此狀態:
(1) 當通過new語句剛創建了一個對象,不和數據庫中的不論什麽記錄相應。
(2) Session的delete()方法能使一個持久化對象或遊離對象轉變為暫時對象。對於遊離對象,delete()方法從數據庫中刪除與它相應的記錄;對於持久化對象。delete()方法從數據庫中刪除與它相應的記錄。而且把它從Session的緩存中刪除。
Persist Objects:
持久實例是不論什麽具有數據庫標識的實例。它有持久化管理器Session統一管理。持久化實例在事務中進行操作的。其狀態在事務結束時同數據庫進行同步。
當事務提交時。通過運行SQL的insert、update、delete語句把內存中的狀態同步到數據庫中。
Session的很多方法都可以觸發Java對象進入持久化狀態,比方說Session的save()把暫時對象轉變為持久化對象。load()或get()返回的對象處於持久化狀態。find()返回的List集合中存放的都是持久化對象。update()、saveOrUpdate()和lock()使遊離對象轉變為持久化對象。
Detached Objects:
Session被關閉後,持久化對象就變成離線對象。離線表示這個對象不再與數據庫保持同步,不再受管理。
當調用Session的close()時,Session的緩存被清,緩存中的全部持久化對象都變為遊離對象。evict()可以從緩存中刪除一個持久化對象,使它變為遊離狀態。
實例分析:
項目結構:
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 > <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">zhudan</property> <property name="hibernate.connection.password">1221</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping resource="zhudan/hibernate/User.hbm.xml"></mapping> </session-factory> </hibernate-configuration>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 > <class name="zhudan.hibernate.User" table="T_User"> <id name="id" column="UserID"> <generator class="uuid"/> </id> <property name="name" column="UserName"></property> <property name="password" column="PassWord"></property> <property name="createTime" column="CreateTime"></property> <property name="expireTime" column="ExpireTime"></property> </class> </hibernate-mapping>HibernateUtils類:
讀取前面配置的hibernate.cfg.xml,建立SessionFactory、Session,關閉Session等。
package zhudan.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class HibernateUtils { private static SessionFactory factory; static{ try{ //讀取hibernate.cfg.xml Configuration cfg=new Configuration().configure(); //建立SessionFactory factory=cfg.buildSessionFactory(); }catch(Exception e){ e.printStackTrace(); } } //獲取Session public static Session getSession(){ return factory.openSession(); } //關閉Session public static void closeSession(Session session){ if(session!=null){ if(session.isOpen()){ session.close(); } } } //SessionFactory public static SessionFactory getSessionFactory(){ return factory; } }ExportDB類:映射表。將hbm.xml生成相應的ddl。
package zhudan.hibernate; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportDB { public static void main(String[] args){ //讀取hibernate.cfg.xml文件 Configuration cfg=new Configuration().configure(); SchemaExport export=new SchemaExport(cfg); export.create(true, true); } }SessionTest類:
package zhudan.hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.Transaction; import junit.framework.TestCase; public class SessionTest extends TestCase { public void testSave1(){ Session session=null; //開啟事務 Transaction tx=null; try{ session=HibernateUtils.getSession(); tx=session.beginTransaction(); //Transient狀態 User user=new User(); user.setName("zhudan"); user.setPassword("zhudan"); user.setCreateTime(new Date()); user.setExpireTime(new Date()); //被session管理。persistent狀態。當對象屬性改變的時候 //清理緩存(臟數據)的時候,會和數據庫同步 session.save(user); //更新上一條數據 user.setName("fanglin1"); session.update(user); //提交事務 tx.commit(); }catch(Exception e){ e.printStackTrace(); if(tx!=null){ tx.rollback(); } }finally{ HibernateUtils.closeSession(session); } //detached狀態 } }在這個樣例中,當New一個User對象時,狀態是Transient Objects,此時數據庫中沒有這條數據,不被Session管理,當在運行保存時。狀態改變為Persist Objects,此時,數據中存在當前數據,被Session管理,一旦事務被提交。運行完此語句後。狀態更改為Detached Objects,此時數據庫中存在此數據。被Session管理。
總結:
持久化封裝了數據訪問細節。為大部分業務邏輯提供了面向對象的接口,降低了數據庫訪問次數,添加了應用程序的運行速度,使其不依賴於底層數據庫和上層業務邏輯實現,更換數據庫時也僅僅是改動配置文件而不用改動代碼。重用性大大提高。
【SSH之旅】一步步學習Hibernate框架(一):關於持久化