日期:2014-05-18 浏览次数:20726 次
package com.comm; //包省略 @SuppressWarnings("unchecked") public class BaseDAOImpl<T, PK extends Serializable> extends HibernateDaoSupport implements BaseDAO<T, PK> { private final static Logger logger = Logger.getLogger(BaseDAOImpl.class); protected Class<T> clazz; public BaseDAOImpl() { } public BaseDAOImpl(Class<T> clazz) { this.clazz = clazz; } public PK create(T o) { return (PK) this.getHibernateTemplate().save(o); } public void create(T o, Serializable pk) { this.getHibernateTemplate().save((String)o, pk); } public void save(T o) { this.getHibernateTemplate().saveOrUpdate(o); } public T find(PK id) { Object o = this.getHibernateTemplate().load(clazz, id); return (T) o; } public T get(PK id) { Object o = this.getHibernateTemplate().get(clazz, id); return (T) o; } public void update(T o) { this.getHibernateTemplate().update(o); } public void delete(PK id) { getHibernateTemplate().delete(find(id)); } public void delete(T o) { this.getHibernateTemplate().delete(o); } public void deleteAll(Collection<T> entities) { getHibernateTemplate().deleteAll(entities); } public List<T> list() { return this.getHibernateTemplate().loadAll(clazz); } /** * 去除select 子句,未考虑union的情况 */ private static String removeSelect(String hql) { Assert.hasText(hql); int beginPos = hql.toLowerCase().lastIndexOf("from"); Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'"); return hql.substring(beginPos); } /** * 去除select 子句,未考虑union的情况 */ private static String removeFirstSelect(String hql) { Assert.hasText(hql); int beginPos = hql.toLowerCase().indexOf("from"); Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'"); return hql.substring(beginPos); } /** * 去除orderby 子句 */ private static String removeOrders(String hql) { Assert.hasText(hql); Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(hql); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, ""); } m.appendTail(sb); return sb.toString(); } public Object getObject(String hql){ Query query = getSession().createQuery(hql); List list = query.list(); if(list == null || list.size() <= 0){ return null; } return list.get(0); } public List list(String hql, int topNumber, Object... args) { Assert.hasText(hql); Query query = getSession().createQuery(hql); for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } query.setMaxResults(topNumber); return (List) query.list(); } public List list(String hql, Object... args) { return this.list(hql, new Pager(), args); } public List listBySQL(String sql, String alias, Class clazz, Object... args) { return this.listBySQL(sql, new Pager(), alias, clazz, args); } public List listBySQL(String sql, Object[] args) { Quer