hibernate中session和query的運用

來源:互聯網
上載者:User

 繼承了HibernateDaoSupport類的類擷取session時,有以下幾個好處:

對於session不瞭解請先看後面的session

1):由於HibernateDaoSupport本身已有擷取session的方法getSession(),所以直接用Session se=this.getSession();來擷取,此時我們執行完了事物操作之後要session.close()或者this.releaseSession(session);關閉session。

插述:hibernate擷取session的幾種方法:

1,Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); ---->最基本的擷取方法

 2,Session session =  new Configuration().configure().buildSessionFactory().openSession();,------>通過設定檔擷取

 Configuration的其他用法
Configuration的configure ()方法還支援帶參數的訪問方式,你可以指定hbm.xml檔案的位置,而不是使用預設的classpath
下面的hibernate.cfg.xml這種方式,例如:
Configuration cfg = new Configuration().configure("myexample.xml");

sessionFactory = new Configuration().buildSessionFactory();

3,SessionFactory
sessionFactory = new Configuration().buildSessionFactory(); sessionFactory.openSession();
  sessionFactory.getCurrentSession();---->第一次死openSession(),後面都是擷取當前session。就可以使記憶體用到最少。與第一種一樣只是getCurrentSession();

4,Session session= this.getSession();如果繼承了hibernateDaoSupport的話。

5,自己寫一個hibernateUtils類,在裡面開啟openSession()。如

A typical transaction should use the following idiom: 官方推薦寫法:

 Session sess = factory.openSession(); Transaction tx; try {     tx = sess.beginTransaction();     //do some work     ...     tx.commit(); } catch (Exception e) {     if (tx!=null) tx.rollback();     throw e;//e.printStackTrace();
 } finally {     sess.close(); } 
Interface Session extends Session(下面是gaiSession中的常用方法) extends  Serializable

 

@1-->掌握session中的幾個基本方法的使用。

createQuery:只能用hql語句進行查詢,此方法和下面的createSQLQuery也可以進行更新等操作,如:session.createQuery(hql)。executeUpdate(); 

以hibernate產生的Bean為對象裝入list返回,返回list集合。調用.list()時產生的SQL:select userid,username from tuser;
調用session.createQuery("from User u").iterator()時產生的SQL:select userid from tuser;可以看出:可以看出list()一次將資料從資料庫中讀出直接填充到List中
iterator()將資料的主鍵從資料庫中讀出,當迴圈這個Iterator時才添加執行:

用途:
  
createSQLQuery:可以用sql語句查詢,以對象數組進行儲存, session.createSQLQuery(sql).addEntity(Dtree.class).list();可以這樣返回list集合

用途:

總結:createSQLQuery  sql語句查詢,直接查表,執行速度比createQuery快,createQuery 根據HQL物件查詢,需要對應檔hbm.xml配置.

3):save方法 

save method stores an object into the database.

儲存方法儲存到資料庫中的對象。                     看老外怎麼寫的 ,翻譯過來真彆扭

That means it insert an entry if the identifier doesn't exist, else it will throw error.

==》如果標識符不存在的話,這意味著它將插入(儲存)一個對象,如果標識符已經存在的話的話,它會拋出錯誤。

If the primary key already present in the table, it cannot be inserted.

==》如果表中已存在主鍵,對象不能插入。

4):saveOrUpdate方法  用於把實體持久化到資料庫中或更新實體。saveOrUpdate方法兼有save和update方法的功能,save和update方法的監聽器都是saveOrUpdate方法對應監聽器的子類。即saveOrUpdate使save或者update方法的組合。可以執行save或者update的所有功能,甚至可以替代save或者update。但是如果我們明確的知道了自己是要儲存還是更新的對象的話,最好還是用save或者update,這樣執行效率會高。

This method calls save() or update() based on the operation.

此方法調用儲存()或update()的基礎上操作。

 If the identifier exists, it will call update method else the save method will be called.

==》如果存在的標識符,它會調用Update方法,否則調用儲存方法。

5):update方法

update method in the hibernate is used for updating the object using identifier

更新方法用於根據指定標識符更新的對象。

If the identifier is missing or doesn't exist, it will throw exception.

==》如果標識符是丟失或不存在,它會拋出異常。

中國版:

saveOrUpdate()方法同時包含了save()與update()方法的功能,如果傳入的參數是臨時對象,就調用save()方法;如果傳入的參數是游離對象,就調用update()方法;如果傳入的參數是持久化對象,那就直接返回。那麼,saveOrUpdate()方法如何判斷一個對象處於臨時狀態還是游離狀態呢?如果滿足以下情況之一,Hibernate就把它作為臨時對象。

  • Java對象的OID取值為null。
  • Java對象具有version屬性並且取值為null。
  • 在對應檔中為<id>元素設定了unsaved-value屬性,並且IOD取值與unsaved-value屬性值匹配。
  • 在對應檔中為version屬性設定了unsaved-value屬性,並且version屬性取值與unsaved-value屬性值

 

6):merge方法 如果在add一個對象之後,如果存在關聯對象,並且需要再同一個hibernate session中進行回顯,則建議使用merge()方法。

http://blog.csdn.net/oldcrane/article/details/3837188

7):persist方法http://www.blogjava.net/dreamstone/archive/2007/07/29/133071.html

8):get方法

9):load方法

其他方法:

1):flush方法

2):clear方法

3):refresh方法

4):evict方法

2):可以this.getHibernateTemplate()。方法來進行hql語句的操作,我們不需要開啟關閉session,串連,會話等這些,hibernate和spring已經幫我們封裝好了。標準格式:直接一句代碼搞定如:this.getHibernateTemplate().delete(dtree);

掌握下面方法的使用:

getHibernateTemplate().save(entity);

getHibernateTemplate().update(entity);

getHibernateTemplate().saveOrUpdate(entity);

getHibernateTemplate().merge(entity);

getHibernateTemplate().persist(entity);

getHibernateTemplate().get(entityClass, id);

getHibernateTemplate().load(entityClass, id);

getHibernateTemplate().clear();

getHibernateTemplate().flush();

getHibernateTemplate().evict(entity);

getHibernateTemplate().refresh(entity);

3):

參考:


Transaction beginTransaction()
          Begin a unit of work and return the associated Transaction object

 Query createQuery(String queryString)
          Create a new instance of Query for the given HQL query string.
 SQLQuery createSQLQuery(String queryString)
          Create a new instance of SQLQuery for the given SQL query string.
http://hi.baidu.com/21xionghua/blog/item/199d43fa59e6908b9e5146ad.html
採用sql查詢,不能直接轉換為list集合,採用下面的方法就可以了
 List catNameList = session.createSQLQuery(sql).addEntity(DocCatalogInfo.class).list();
如果是關聯查詢出來的是哪個對象?怎麼處理?
select * from t_user a,t_user_role b where a.c_userid=b.c_userid and a.c_username='admin'
sql查詢可以更換為list查詢更精確的就是string[]數組的集合:
select C_ROLEID from t_user a,t_user_role b where a.c_userid=b.c_userid and a.c_username='admin'
[POWERUSERS, ADMINS, USERS, GROUPADMINS]
 
void delete(Object object)           從資料庫中移除持久化(persistent)對象的執行個體
get(Class clazz, Serializable id)           根據給定標識和實體類返回持久化對象的執行個體,如果沒有合格持久化對象執行個體則返回null。
getSessionFactory()           擷取建立這個session的SessionFactory執行個體。
save(Object object)           首先為給定的自由狀態(Transient)的對象(根據配置)產生一個標識並賦值,然後將其持久化。
void saveOrUpdate(Object object)           根據給定的執行個體的識別屬性的值(註:可以指定unsaved-value。一般預設null。)來決定執行 save() 或update()操作。void update(Object object)           根據給定的detached(游離狀態)對象執行個體的標識更新對應的持久化執行個體。query
http://developer.51cto.com/art/200906/130073.htm
  
  1. String hql=”from User user ”;  
  2. List list=session.CreateQuery(hql).list(); 
上面的代碼執行結果是,查詢出User實體物件所對應的所有資料,而且將資料封裝成User實體物件,並且放入List中返回。

 
 Iterator iterate()
          Return the query results as an Iterator.
 List list()
          Return the query results as a List.

 
 int executeUpdate()
          Execute the update or delete statement.
  

批次更新:通過這種方式我們可以在Hibernate3中,一次性完成批量資料的更新,對效能的提高是相當的可觀。同樣也可以通過類似的方式來完成delete操作,如下面的代碼:

  1. Transaction trans=session.beginTransaction();  
  2. String hql=”delete from User user where user.age=18”;  
  3. Query queryupdate=session.createQuery(hql);  
  4. int ret=queryupdate.executeUpdate();  
  5. trans.commit();
  6. 如果使用的是getCurrentSession來建立session的話,在commit後,session就自動被關閉了,也就是不用再session.close()了。但是如果使用的是openSession或者getSession()方法建立的session的話,那麼必須顯示的關閉session,也就是調用session.close()方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.