接上篇所说,如果懂得这个思想,其实很简单了,况且有spring的HibernateDaoSupport坐阵,你的代码会更精简,会更优化。话不多说,贴上代码先看一下吧:
java 代码
- /**
- * 负责为单个Entity对象提供CRUD操作的Hibernate DAO基类.
子类只要在类定义时指定所管理Entity的Class,
- * 即拥有对单个Entity对象的CRUD操作.
- *
- *
- */
- @SuppressWarnings("unchecked")
- abstract public class HibernateBaseDao extends HibernateDaoSupport {
- protected Class entityClass;// DAO所管理的Entity类型.
- /**
- * 在构造函数中将泛型T.class赋给entityClass.
- */
- public HibernateBaseDao() {
- entityClass = GenericsUtils.getSuperClassGenricType(getClass());
- }
- /**
- * 取得entityClass.JDK1.4不支持泛型的子类可以抛开Class entityClass,重载此函数达到相同效果。
- */
- protected Class getEntityClass() {
- return entityClass;
- }
- /**
- * 根据ID获取对象.
- *
- * @see HibernateGenericDao#getId(Class,Object)
- */
- public T load(Serializable id) {
- return (T) getHibernateTemplate().load(getEntityClass(), id);
- }
- /**
- * 根据ID获取对象,使用hinbernate get().
- *
- * @see HibernateGenericDao#getId(Class,Object)
- */
- public T get(Serializable id) {
- return (T) getHibernateTemplate().get(getEntityClass(), id);
- }
- /**
- * 获取全部对象
- *
- * @see HibernateGenericDao#getAll(Class)
- */
- public List getAll() {
- return getHibernateTemplate().loadAll(getEntityClass());
- }
- /**
- * 获取全部对象,带排序参数.
- *
- */
- public List getAll(String orderBy, boolean isAsc) {
- Assert.hasText(orderBy);
- if (isAsc)
- return getHibernateTemplate().findByCriteria(
- DetachedCriteria.forClass(getEntityClass()).addOrder(
- Order.asc(orderBy)));
- else
- return getHibernateTemplate().findByCriteria(
- DetachedCriteria.forClass(getEntityClass()).addOrder(
- Order.desc(orderBy)));
- }
- /**
- * 保存对象.
- */
- public Serializable save(Object o) {
- return getHibernateTemplate().save(o);
- }
- /**
- * 更新对象
- *
- * @param o
- */
- public void update(Object o) {
- getHibernateTemplate().update(o);
- }
- /**
- * 保存或更新对象
- *
- * @param o
- */
- public void saveOrUpdate(Object o) {
- getHibernateTemplate().saveOrUpdate(o);
- }
- /**
- * 删除对象.
- */
- public void remove(Object o) {
- getHibernateTemplate().delete(o);
- }
- /**
- * 根据ID移除对象.
- *
- * @see HibernateGenericDao#removeById(Class,Serializable)
- */
- public void removeById(Serializable id) {
- remove(load(id));
- }
- public void flush() {
- getHibernateTemplate().flush();
- }
- public void clear() {
- getHibernateTemplate().clear();
- }
- /**
- * 创建Query对象.
- * 对于需要first,max,fetchsize,cache,cacheRegion等诸多设置的函数,可以在返回Query后自行设置.
- * 留意可以连续设置,如下:
- *
- * @param values
- * 可变参数.
- */
- public Query createQuery(String hql, Object... values) {
- Assert.hasText(hql);
- Query query = getSession().createQuery(hql);
- for (int i = 0; i < values.length; i++) {
- query.setParameter(i, values[i]);
- }
- return query;
- }
- /**
- * 取得Entity的Criteria.
- *
- */
- public Criteria createCriteria() {
- return getSession().createCriteria(getEntityClass());
- }
- /**
- * 取得Entity的Criteria.
- *
- */
- public Criteria createCriteria(Criterion... criterions) {
- Criteria criteria = createCriteria();
- for (Criterion c : criterions) {
- criteria.add(c);
- }
- return criteria;
- }
- /**
- * 取得Entity的Criteria,带排序参数.
- *
- */
- public Criteria createCriteria(String orderBy, boolean isAsc,
- Criterion... criterions) {
- Assert.hasText(orderBy);
- Criteria criteria = createCriteria(criterions);
- if (isAsc)
- criteria.addOrder(Order.asc(orderBy));
- else
- criteria.addOrder(Order.desc(orderBy));
- return criteria;
- }
- /**
- * 根据hql查询,直接使用HibernateTemplate的find函数.
- *
- * @param values
- * 可变参数,见{@link #createQuery(String,Object...)}
- */
- public List find(String hql, Object... values) {
- Assert.hasText(hql);
- return getHibernateTemplate().find(hql, values);
- }
- /**
- * 根据属性名和属性值查询对象.
- *
- * @return 符合条件的对象列表
- */
- public List findBy(String propertyName, Object value) {
- Assert.hasText(propertyName);
- return createCriteria(Restrictions.eq(propertyName, value)).list();
- }
- /**
- * 根据属性名和属性值查询对象,带排序参数.
- */
- public List findBy(Class entityClass, String propertyName,
- Object value, String orderBy, boolean isAsc) {
- Assert.hasText(propertyName);
- Assert.hasText(orderBy);
- return createCriteria(orderBy, isAsc,
- Restrictions.eq(propertyName, value)).list();
- }
- /**
- * 根据属性名和属性值查询对象,带排序参数.
- *
- * @return 符合条件的对象列表
- */
- public List findBy(String propertyName, Object value, String orderBy,
- boolean isAsc) {
- return findBy(getEntityClass(), propertyName, value, orderBy, isAsc);
- }
- /**
- * 根据属性名和属性值查询单个对象.
- *
- * @return 符合条件的唯一对象 or null
- */
- public T findUniqueBy(String propertyName, Object value) {
- Assert.hasText(propertyName);
- return (T) createCriteria(Restrictions.eq(propertyName, value))
- .uniqueResult();
- }
- /**
- * 分页查询函数,使用hql.
- *
- * @param pageNo
- * 页号,从1开始.
- */
- public Page pagedQuery(String hql, int pageNo, int pageSize,
- Object... values) {
- Assert.hasText(hql);
- Assert.isTrue(pageNo >= 1, "pageNo should start from 1");
- // Count查询
- String countQueryString = " select count (*) "
- + removeSelect(removeOrders(hql));
- List countlist = getHibernateTemplate().find(countQueryString, values);
- long totalCount = (Long) countlist.get(0);
- if (totalCount < 1)
- return new Page();
- // 实际查询返回分页对象
- int startIndex = Page.getStartOfPage(pageNo, pageSize);
- Query query = createQuery(hql, values);
- List list = query.setFirstResult(startIndex).setMaxResults(pageSize)
- .list();
- return new Page (startIndex, totalCount, pageSize, list);
- }
- /**
- * 分页查询函数,使用已设好查询条件与排序的
Criteria
. - *
- * @param pageNo
- * 页号,从1开始.
- * @return 含总记录数和当前页数据的Page对象.
- */
- public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) {
- Assert.notNull(criteria);
- Assert.isTrue(pageNo >= 1, "pageNo should start from 1");
- CriteriaImpl impl = (CriteriaImpl) criteria;
- // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
- Projection projection = impl.getProjection();
- List orderEntries;
- try {
- orderEntries = (List) BeanUtils.forceGetProperty(impl,
- "orderEntries");
- BeanUtils.forceSetProperty(impl, "orderEntries", new ArrayList());
- } catch (Exception e) {
- throw new InternalError(" Runtime Exception impossibility throw ");
- }
- // 执行查询
- int totalCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- // 将之前的Projection和OrderBy条件重新设回去
- criteria.setProjection(projection);
- if (projection == null) {
- criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
- }
- try {
- BeanUtils.forceSetProperty(impl, "orderEntries", orderEntries);
- } catch (Exception e) {
- throw new InternalError(" Runtime Exception impossibility throw ");
- }
- // 返回分页对象
- if (totalCount < 1)
- return new Page();
- int startIndex = Page.getStartOfPage(pageNo, pageSize);
- List list = criteria.setFirstResult(startIndex).setMaxResults(
- pageSize).list();
- return new Page (startIndex, totalCount, pageSize, list);
- }
- /**
- * 分页查询函数,根据entityClass和查询条件参数创建默认的
Criteria
. - *
- * @param pageNo
- * 页号,从1开始.
- * @return 含总记录数和当前页数据的Page对象.
- */
- public Page pagedQuery(int pageNo, int pageSize, Criterion... criterions) {
- Criteria criteria = createCriteria(criterions);
- return pagedQuery(criteria, pageNo, pageSize);
- }
- /**
- * 分页查询函数,根据entityClass和查询条件参数,排序参数创建默认的
Criteria
. - *
- * @param pageNo
- * 页号,从1开始.
- * @return 含总记录数和当前页数据的Page对象.
- */
- public Page pagedQuery(int pageNo, int pageSize, String orderBy,
- boolean isAsc, Criterion... criterions) {
- Criteria criteria = createCriteria(orderBy, isAsc, criterions);
- return pagedQuery(criteria, pageNo, pageSize);
- }
- /**
- * 判断对象某些属性的值在数据库中是否唯一.
- *
- * @param uniquePropertyNames
- * 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password"
- */
- public boolean isUnique(Object entity, String uniquePropertyNames) {
- Assert.hasText(uniquePropertyNames);
- Criteria criteria = createCriteria().setProjection(
- Projections.rowCount());
- String[] nameList = uniquePropertyNames.split(",");
- try {
- // 循环加入唯一列
- for (String name : nameList) {
- criteria.add(Restrictions.eq(name, PropertyUtils.getProperty(
- entity, name)));
- }
- // 以下代码为了如果是update的情况,排除entity自身.
- String idName = getIdName(getEntityClass());
- // 取得entity的主键值
- Serializable id = getId(entity);
- // 如果id!=null,说明对象已存在,该操作为update,加入排除自身的判断
- if (id != null)
- criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
- } catch (Exception e) {
- ReflectionUtils.handleReflectionException(e);
- }
- return (Integer) criteria.uniqueResult() == 0;
- }
- /**
- * 取得对象的主键值,辅助函数.
- */
- public Serializable getId(Object entity) throws NoSuchMethodException,
- IllegalAccessException, InvocationTargetException {
- Assert.notNull(entity);
- Assert.notNull(getEntityClass());
- return (Serializable) PropertyUtils.getProperty(entity,
- getIdName(getEntityClass()));
- }
- /**
- * 取得对象的主键名,辅助函数.
- */
- public String getIdName(Class clazz) {
- Assert.notNull(clazz);
- ClassMetadata meta = getSessionFactory().getClassMetadata(clazz);
- Assert.notNull(meta, "Class " + clazz
- + " not define in hibernate session factory.");
- String idName = meta.getIdentifierPropertyName();
- Assert.hasText(idName, clazz.getSimpleName()
- + " has no identifier property define.");
- return idName;
- }
- /**
- * 去除hql的select 子句,未考虑union的情况,用于pagedQuery.
- *
- * @see #pagedQuery(String,int,int,Object[])
- */
- private static String removeSelect(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);
- }
- /**
- * 去除hql的orderby 子句,用于pagedQuery.
- *
- * @see #pagedQuery(String,int,int,Object[])
- */
- 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();
- }
- /**
- * 根据页码和每页的长度返回对象集合
- *
- * @param pageNo
- * 页码
- * @param pageSize
- * 每页的长度
- * @return
- */
- public List getObjects(int pageNo, int pageSize) {
- Criteria criteria = this.createCriteria();
- return this.pagedQuery(criteria, pageNo, pageSize).getResult();
- }
- }
有了这个DAO后,你再让其它的实体DAO继承这个BASEDAO,比如:
java 代码
- public class ProductDAO extends HibernateBaseDao {
- //public void otherMethod(){...}
- }
就大功告成,所谓的OO,就让泛型帮你完成,烦人的对象转换就此终结。
有兴趣的朋友可以参考springside的源码,它更详细。