Posted on 2007-09-19 13:25
優雅Dě頽廢 閱讀(843)
評論(0) 編輯 收藏 所屬分類:
Spring
Spring用回調HibernateCallBack方法實現持久層一些功能,當這些功能不能滿足需求時,我們也可以自已來重寫HibernateCallBack,例:
public class UsersDAO extends HibernateDaoSupport {
......
public List getUsers() {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session s) throws HibernateException,
SQLException {
Query query = s.createQuery("From Users AS user ORDER BY user.username DESC");
List list = query.list();
return list;
}
});
}
......
}
但是這樣的代碼很難讓人理解,可以將其打包
package com.notepad.comm;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
public class HQLCallBackUtil implements HibernateCallback {
private String hql;
public HQLCallBackUtil(){
}
public HQLCallBackUtil(String hql){
this.hql=hql;
}
public String getHql() {
return hql;
}
public void setHql(String hql) {
this.hql = hql;
}
public Object doInHibernate(Session s) throws HibernateException,
SQLException {
if (hql == null || hql.equals("")) {
throw new HibernateException("Can't execute NULL hql!");
}
return s.createQuery(hql).list();
}
}
然后可以通過如下代碼進行調用
public class UsersDAO extends HibernateDaoSupport {
......
public List getUsers() {
HQLCallBackUtil callBack=new HQLCallBackUtil();
callBack.setHql("From Users AS user ORDER BY user.username DESC");
return this.getHibernateTemplate().executeFind(callBack);
}
......
}