续上篇,时间关系代码实现但是略有不同,不同点请各位同学自行解决。 package net.hlin.common.dao; import java.io.Serializable; import java.sql.SQLException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.hlin.common.vo.PageBean; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class GenericDaoSupport extends HibernateDaoSupport implements GenericDao { public void add(Object entity) { getHibernateTemplate().save(entity); } public <T> void delete(Class<T> clazz, Serializable id) { getHibernateTemplate().delete(getHibernateTemplate().get(clazz, id)); } @SuppressWarnings("unchecked") public <T> T find(Class<T> clazz, Serializable id) { return (T) getHibernateTemplate().get(clazz, id); } @SuppressWarnings("unchecked") public <T> List<T> find(String hql, Object... params) { return getHibernateTemplate().find(hql, params); } @SuppressWarnings("unchecked") public <T> List<T> loadAll(Class<T> clazz) { return getHibernateTemplate().loadAll(clazz); } public void update(Object entity) { getHibernateTemplate().update(entity); } @SuppressWarnings("unchecked") public <T> List<T> find(final PageBean pb, final String hql, final Object... params) { return getHibernateTemplate().executeFind(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); int first = pb.getPageNumber() * pb.getPageSize(); for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } query.setFirstResult(first); query.setMaxResults(pb.getPageSize()); List<T> list = query.list(); query = session.createQuery("select count(*) from (" + removeOrders(hql) + ")"); Long total = (Long) query.uniqueResult(); pb.setTotal(total); return list; } }); } private String removeOrders(String hql) { Pattern pattern = Pattern.compile("order//s*by[//w|//W|//s|//S]*", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(hql); StringBuffer buf = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buf, ""); } matcher.appendTail(buf); return buf.toString(); } }