標籤:使用 insert connect conf cas catch nal object rollback
在不引用不論什麼架構下,我們會通過平庸的代碼不停的對資料庫進行操作,產生了非常多冗餘的可是又有規律的底層代碼,這樣頻繁的操作資料庫和大量的底層代碼的反覆書寫極大的浪費了程式人員的書寫。就在這樣一種情況下,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()可以從緩衝中刪除一個持久化對象,使它變為游離狀態。
執行個體分析:
項目結構:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGFuZGFuem1j/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >
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.xmlConfiguration cfg=new Configuration().configure();//建立SessionFactoryfactory=cfg.buildSessionFactory();}catch(Exception e){e.printStackTrace();}}//擷取Sessionpublic static Session getSession(){return factory.openSession();}//關閉Sessionpublic static void closeSession(Session session){if(session!=null){if(session.isOpen()){session.close();}}}//SessionFactorypublic 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架構(一):關於持久化