1. 程式人生 > >SSH應用--Hibernate 訪問資料庫的三種方法比較

SSH應用--Hibernate 訪問資料庫的三種方法比較

DAO開發
(1)以下兩者都需在Spring XML配置檔案中,註冊Bean(實現類)來依賴注入SessionFactory.
(2.1)Spring 中進行事務管理的通常方式是利用AOP(面向切片程式設計)的方式,為普通java類封裝事務控制,它是通過動態代理實現的,由於介面是
延遲例項化的, spring在這段時間內通過攔截器,載入事務切片。原理就是這樣,具體細節請參考jdk中有關動態代理的文件。本文主要講解
如何在spring中進行事務控制。
(2.2)動態代理的一個重要特徵是,它是針對介面的,所以我們的DAO要通過動態代理來讓spring接管事務,就必須在DAO前面抽象出一個介面. 當然
如果沒有這樣的介面,那麼spring會使用CGLIB來解決問題,但這不是spring推薦的方式.


(一)直接使用Hibernate API (不推薦使用)
public class DaoImp implate Dao{
private SessionFactory sessionFactory;
private static String hql = "from User u where u.username=? ";

public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}

public boolean isValidUser(String username) {

try{
List userList = sessionFactory.getCurrentSession().creatQuery(hql).setParameter(0,username).list();
if (userList.size() > 0) {
return true;
} catch (HibernateException ex){
throw converHibernaterAccessException(ex);

}
}

優點:與Spring框架完全分離
缺點:(1)無法使用Spring框架封裝所提供的額外功能.如,直接使用Hibernate API 需用try...catch()處理HibernateException異常.

(2)需在實現類中加入setSessionFactory(SessionFactory sessionFactory)屬性,接收依賴注入的SessionFactory.

(二)繼承 Spring 的 HibernateDaoSupport 使用 HibernateTemplate (不推薦使用getSession())
public class DaoImp extend HibernateDaoSupport implates Dao{
  //private SessionFactory sessionFactory;
private static String hql = "from User u where u.username=? ";

  //public void setSessionFactory(SessionFactory sessionFactory){
// this.sessionFactory=sessionFactory;
//}


public boolean isValidUser(String username) {
  // try{
// List userList = sessionFactory.getCurrentSession().creatQuery(hql).setParameter(0,username).list();

List userList = getHibernateTemplate().find(hql,username);
if (userList.size() > 0) {
return true;
  // } catch (HibernateException ex){
// throw converHibernaterAccessException(ex);
// } 

}

public boolean isValidUser(String username,String password) throw DataAccessException {
 Session session = getSession(); //不推薦使用,用完後需手動關閉
String[] userlist=new String[2];
userlist[0]=username;
userlist[1]=password;
try{
List userList = session.find(hql,userlist);  //Hibernate語句;
session.close();
if (userList.size() > 0) {
return true;
} catch (HibernateException ex){
throw converHibernaterAccessException(ex);

}
}

特點:對HibernateTemplate沒有提供的功能,可以直接呼叫HibernateDaoSuppor物件的getSession()方法(極其不推薦使用)得到Session物件例項用try{ Hibernate API }catch (HibernateException ex )操作.

(三)對 HibernateTemplate 沒有提供的功能, 還可以用HibernateCallback 回撥的方法管理資料庫. (極其推薦)


public List getListForPage ( final String hql , final int offset , final int length ) {

List list = getHibernateTemplate().executeFind ( new HibernateCallback ( ) {
public Object doInHibernate ( Session session ) throws HibernateException, SQLException {
Query query = session.createQuery ( hql ) ;
query.setFirstResult ( offset ) ;
query.setMaxResults ( length ) ;
List list = query.list ( ) ;
return list ;
}
}) ;
return list ;
}

?

?

?

spring+hibernate架構中Dao訪問資料庫的幾種方法
在spring+hibernate的架構中,訪問資料庫有幾種方法,按spring依賴注入來區分有3種,在這之前先再來了解一下spring的依賴注入,spring主要的兩大核心就是IOC(控制反轉)和AOP(面向切面程式設計),控制反轉就是控制轉移,從以往由Bean去控制要呼叫的介面或其他資源轉移給容器,由容器來尋找並例項化要呼叫的介面,也可以解釋成依賴注入,即在spring配置檔案中把要呼叫的介面、設定、構造子配置給Bean。這邊是以依賴注入來區分為sessionFactory、hibernateTemplate、jdbcTemplate,本質上劃分只有hibernateTemplate和jdbcTemplate這兩種。1、注入sessionFactory
在spring配置檔案中,對Dao注入sessionFactory,即:
<bean id="classDao" class="cn.jmu.data.dao.impl.ClassImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
這邊sessionFactory依賴注入的不是給Dao層中的類,而是給HibernateDaoSupport,見spring原始檔org/springframework/orm/hibernate3/support/HibernateDaoSupport.java裡面,就有sessionFactory的set、get操作:public final void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);//通過sessionFactory來生成hibernateTemplate
}public final SessionFactory getSessionFactory() {
return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
}所以在Dao層中類繼承HibernateDaoSupport,即可通過this.getHibernateTemplate()來對資料庫進行操作,
更新資料:this.getHibernateTemplate().update(bo);
查詢資料:this.getHibernateTemplate().find(bo);
新增資料:this.getHibernateTemplate().save(bo) ;
刪除資料:this.getHibernateTemplate().delete(bo);
從上面可以看出spring+hibernate的強大威力,存取資料不用像以往jdbc那樣,要寫一大串try,catch語句,還要連線資料庫,用完再關閉資料庫連線,而用一條語句就可以搞定。
這裡sessionFactory由spring自動自動連線、關閉,當然你也可以手動來連線、關閉,如下面採用的方法:
Session session=this.getHibernateTemplate().getSessionFactory().openSession();
Transaction tx=session.beginTransaction();

String str="hql";
Query query=session.createQuery(str);
List list=query.list();

session.load(bo,ID);
session.delete(bo);

session.save(bo); 

session.load(bo,ID);
session.update(