阅读更多
百事通信息网
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);
}
......
}
这样是不是感觉简单很多呢!