Hibernate的重要技術(shù)簡介
Hibernate技術(shù)有很多值得學(xué)習(xí)的地方,這里我們主要介紹Hibernate技術(shù)的一些強大功能,包括Hibernate技術(shù)技術(shù)開發(fā)流程等方面。
Hibernate技術(shù)開發(fā)流程:
1.配置文件:
@.properties格式的
@.xml格式的(常用hibernate.cfg.xml)(放在src下面或者是wen-inf\classes下面)
- SessionFactory sf=new Configuration().configure().buildSessionFactory();
- 或者SessionFactory sf=new Configuration().configure("db.cfg.xml").buildSessionFactory();
2.編寫映射文件:
例如:User.hbm.xml 映射文件的編寫有很多內(nèi)容,可以采用相關(guān)的根據(jù)自動生成映射文件,在這里就不介紹了
3.寫持久化類:
例如:User.java
4.在編寫DAO之前先寫HibernateSessionFactory類
- package com.wuxiaoxiao.hibernate;
- import org.hibernate.Session;
- import org.hibernate.HibernateException;
- import org.hibernate.cfg.Configuration;
- public class HibernateSessionFactory{
- private static final String CONFIG_FILE_LOCATION="/hibernate.cfg.xml";
- private static final ThreadLocal threadLocal=new ThreadLocal();
- private static final Configuration cfg=new Configuration();
- private static org.hibernate.SessionFactory sessionFactory;
- //取得session
- public static Session currentSession()throws HibernateException{
- Session session=threadLocal.get();
- if(session==null){
- if(sessionFactory==null){
- try{
- cfg.configuration(CONFIG_FILE_LOCATION);
- sessionFactory=cfg.buildSessionFactory();
- }catch(Exception e){
- System.err.println("%%%Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- session=sessionFactory.openSession();
- threadLocal.set(session);
- }
- return session;
- }
- //關(guān)閉session
- public static void closeSession()throws HibernateException{
- Session session=(Session)threadLocal.get();
- threadLocal.set(null);
- if(session!=null)
- session.close();
- }
- }
threadLocal是thread local variable,為每一個訪問它的線程都提供一個變量值的副本,是每一個線程都可以獨立的改變自己的副本,而不會和其他線程的副本沖突。ThreadLocal有三個主要的方法:initValue()初始化變量值,get(),set(Object)例子:
- public class ConnectionFactory{
- private fianl String URL="jdbc:mysql://localhsot/mysatabase";
- private static ThreadLocal<Connection> connectionHolder=new ThreadLocal<Connection>(){
- public COnnection initValue(){
- try{
- return DriverManager.getConnection(URL);}catch(Exception e){}
- }
- };
- public Connection getConnection(){
- return connectionHolder.get();
- }
- }
5.編寫DAO例如:
- public User getUser(String username)throws HibernateException{
- Session session=null;
- Transaction tx=null;
- User user=null;
- try{
- session=HibernateSessionFactory.currentSession();
- tx=session.beginTransaction();
- Query query=session.createQuery("from User where username=?");
- query.setString(0,username.trim());
- user=(User)query.uniqueResult();
- query=null;
- tx.commit();
- }catch(HibernateException e){throw e;
- }finally{
- if(tx!=null)
- tx.rollback();
- HibernateSessionFactory.closeSession();
- }
- return user;
- }
6.編寫service類
public boolean valid(String username,String password){}
下面主要介紹session操縱數(shù)據(jù)庫@對象的狀態(tài):
Hibernate定義并支持下列對象狀態(tài)(state):
瞬時(Transient) - 由new操作符創(chuàng)建,且尚未與Hibernate Session 關(guān)聯(lián)的對象被認(rèn)定為瞬時(Transient)的。瞬時(Transient)對象不會被持久化到數(shù)據(jù)庫中,也不會被賦予持久化標(biāo)識(identifier)。 如果瞬時(Transient)對象在程序中沒有被引用,它會被垃圾回收器(garbage collector)銷毀。 使用Hibernate Session可以將其變?yōu)槌志?Persistent)狀態(tài)。(Hibernate會自動執(zhí)行必要的SQL語句)
持久(Persistent) - 持久(Persistent)的實例在數(shù)據(jù)庫中有對應(yīng)的記錄,并擁有一個持久化標(biāo)識(identifier)。 持久(Persistent)的實例可能是剛被保存的,或剛被加載的,無論哪一種,按定義,它存在于相關(guān)聯(lián)的Session作用范圍內(nèi)。 Hibernate會檢測到處于持久(Persistent)狀態(tài)的對象的任何改動,在當(dāng)前操作單元(unit of work)執(zhí)行完畢時將對象數(shù)據(jù)(state)與數(shù)據(jù)庫同步(synchronize)。 開發(fā)者不需要手動執(zhí)行UPDATE。將對象從持久(Persistent)狀態(tài)變成瞬時(Transient)狀態(tài)同樣也不需要手動執(zhí)行DELETE語句。
脫管(Detached) - 在數(shù)據(jù)庫中存在記錄,但不與session關(guān)聯(lián)!與持久(Persistent)對象關(guān)聯(lián)的Session被關(guān)閉后,對象就變?yōu)槊摴?Detached)的。 對脫管(Detached)對象的引用依然有效,對象可繼續(xù)被修改。脫管(Detached)對象如果重新關(guān)聯(lián)到某個新的Session上, 會再次轉(zhuǎn)變?yōu)槌志?Persistent)的(在Detached其間的改動將被持久化到數(shù)據(jù)庫)。 這個功能使得一種編程模型,即中間會給用戶思考時間(user think-time)的長時間運行的操作單元(unit of work)的編程模型成為可能。 我們稱之為應(yīng)用程序事務(wù),即從用戶觀點看是一個操作單元(unit of work)
@使用sve()保存對象,使之成為持久化
- Session session=HibernateSessionFactory.currentSession();
- User user=new User();
- user.setName("wuxiaoxiao");
- user.setPassword(123456);
- session.save(user);
@使用load()裝在對象
- User user=(User)session.load(User.class,new Integer(1));
若對象不存在就會拋出無法修復(fù)的異常
@使用get()裝在對象
- User user=(User)session.get(User.class,new Integer(4));
若對象不存在的話,就返回null @使用flush()強制提交刷新
- User user=(User)session.get(User.class,new Integer(4));
- user.setUsername("ranran");
- user.setPassword("123456");
- session.flush();
對user的更新是在同一個session中,不需要用update()或者saveOrUpdate()
@使用delete()移除持久化對象
- User user=(User)session.get(User.class,new Integer(4));
- session.delete(user);
- session.flush();
@使用update()方法提交托管狀態(tài)的對象
update()用于根據(jù)給定的托管對象實例的標(biāo)示更新對應(yīng)的持久化實例!如果傳入一個持久化對象,那么update()方法就是多余的。如果傳入臨時狀態(tài)的對象就會出錯,除非認(rèn)為的給臨時地給對象指定一個id。不管傳入的是什么狀態(tài)的對象,數(shù)據(jù)庫中必須要有一條記錄與這個對象的id相對應(yīng),否則拋出異常!
@saveOrUpdate()傳遞的對象在數(shù)據(jù)庫中若存在就更新,否則就插入!他和update()主要是處理托管狀態(tài)的對象!
@使用refresh()強制裝在對象,如果數(shù)據(jù)庫中使用了觸發(fā)器來處理對象的而某些屬性,這個方法就更有用了!
- session.save(user);
- session.flush();
- session.refresh(user);
使用Transaction管理事務(wù)
例子:如上面編寫DAO的例子 使用Query進行HQL查詢 @不帶參數(shù)的查詢
- Query query=session.createQuery("from User");
@帶參數(shù)的查詢
- Query query=session.createQuery("from User where username=:username");
- query.setString("username","wuxiaoxiao");
- 或者
- List names=new ArrayList();
- names.add("wuxiaoxiao");
- names.add("ranran");
- Query query=session.createQuery("from User where username in (:namelist)");
- query.setParameterList("namelist",names);
- 或者
- Query query=session.createQuery("from User where username=?");
- query.setSrting(0,"wuxiaoxiao");
@取得list結(jié)果集
List list=query.list();
@取得迭代列表結(jié)果集
- Iterator iterator1=query.iterator();
- 或者
- Iterator iterator2=query.list().iterator();
- while(iterator.hasNext())
- User user=(User)iterator2.next();
@取得一個對象
- Query query=session.createQuery("from User where username=?");
- query.setString(0,"wuxiaoxiao");
- User user=(User)query.uniqueResult();
@標(biāo)量查詢
- Iterator results = sess.createQuery(
- "select user.name,count(user.email) from User user " +
- "group by user.name")
- .list()
- .iterator();
- while ( results.hasNext() ) {
- Object[] row = (Object[]) results.next();
- String type = (String) row[0];
- Integer count = (Integer) row[1];
- .....
- }
@分頁查詢
- Query q = sess.createQuery("from DomesticCat cat");
- q.setFirstResult(20);
- q.setMaxResults(10);
- List cats = q.list();
@創(chuàng)建sql查詢
使用Criteria進行條件查詢
略.............
【編輯推薦】