说明:这里的代码是我参考了springside的源代码后作了一些比较小的改动,这里没有给出完整的例子,只是讨论一下核心的代码)
这里想说的代码主要是泛型DAO层的应用与分页的写法.
分页,采用了hibernate的一些API来分页,这里同时采用了两种分页方式,CriteriaPage分页方式,适用于多表单时查询后分页用的,而第二种方式是采用Hql语句查询后分页的.代码如下:
CriteriaPage.java文件:
- package org.mmc.commons;
-
- import java.util.ArrayList;
- import java.util.List;
-
- import org.hibernate.Criteria;
- import org.hibernate.criterion.CriteriaSpecification;
- import org.hibernate.criterion.Projection;
- import org.hibernate.criterion.Projections;
- import org.hibernate.impl.CriteriaImpl;
- import org.hibernate.impl.CriteriaImpl.OrderEntry;
- import org.mmc.utils.BeanUtils;
-
-
-
-
-
-
- public class CriteriaPage {
-
-
-
-
- public static Page getPageInstance(Criteria criteria, int pageNo, int pageSize) {
-
- return CriteriaPage.getPageInstanceByCount(criteria, pageNo, pageSize);
- }
-
-
-
-
- protected static Page getPageInstanceByCount(Criteria criteria, int pageNo, int pageSize) {
- CriteriaImpl impl = (CriteriaImpl) criteria;
-
-
- Projection projection = impl.getProjection();
- List orderEntries;
- try {
- orderEntries = (List) BeanUtils.getPrivateProperty(impl, "orderEntries");
- BeanUtils.setPrivateProperty(impl, "orderEntries", new ArrayList());
- }
- catch (Exception e) {
- throw new InternalError(" Runtime Exception impossibility throw ");
- }
-
-
- int totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
-
-
- criteria.setProjection(projection);
- if (projection == null) {
- criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
- }
-
- try {
- BeanUtils.setPrivateProperty(impl, "orderEntries", orderEntries);
- } catch (Exception e) {
- throw new InternalError(" Runtime Exception impossibility throw ");
- }
-
- return getPageResult(criteria, totalCount, pageNo, pageSize);
- }
-
-
-
-
- private static Page getPageResult(Criteria criteria, int totalCount, int pageNo, int pageSize) {
- 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);
- }
-
- }
-
HqlPage.java文件的代码
Page.java文件的源代码如下:
分页的改造已经完成,现在重构一下DAO层的写法,利用了spring对hibernate支持的一些的API.
DAO层:
AbstractHibernateDao.java的源代码
- package org.mmc.dao;
-
- import org.apache.commons.beanutils.PropertyUtils;
- import org.apache.commons.lang.StringUtils;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.hibernate.Criteria;
- import org.hibernate.criterion.MatchMode;
- import org.hibernate.criterion.Order;
- import org.hibernate.criterion.Projections;
- import org.hibernate.criterion.Restrictions;
- import org.springframework.orm.ObjectRetrievalFailureException;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.util.Assert;
- import org.springframework.util.CollectionUtils;
- import org.mmc.utils.GenericsUtils;
-
- import java.io.Serializable;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
-
-
-
-
-
-
- abstract public class AbstractHibernateDao extends HibernateDaoSupport {
-
- protected Log logger = LogFactory.getLog(getClass());
-
-
-
-
- protected Class entityClass;
-
-
-
-
-
- protected Class getEntityClass() {
- return entityClass;
- }
-
-
-
-
- public AbstractHibernateDao() {
- entityClass = GenericsUtils.getGenericClass(getClass());
- }
-
- public T get(Serializable id) {
- T o = (T) getHibernateTemplate().get(getEntityClass(), id);
- if (o == null)
- throw new ObjectRetrievalFailureException(getEntityClass(), id);
- return o;
- }
-
- public List getAll() {
- return getHibernateTemplate().loadAll(getEntityClass());
- }
-
- public void save(Object o) {
- getHibernateTemplate().saveOrUpdate(o);
- }
-
- public void removeById(Serializable id) {
- remove(get(id));
- }
-
- public void remove(Object o) {
- getHibernateTemplate().delete(o);
- }
-
- public List find(String hsql, Object... values) {
- if (values.length == 0)
- return getHibernateTemplate().find(hsql);
- else
- return getHibernateTemplate().find(hsql, values);
- }
-
-
-
-
-
-
- public T findUniqueBy(String name, Object value) {
- Criteria criteria = getSession().createCriteria(getEntityClass());
- criteria.add(Restrictions.eq(name, value));
- return (T) criteria.uniqueResult();
- }
-
-
-
-
-
-
- public List findBy(String name, Object value) {
- Assert.hasText(name);
- Criteria criteria = getSession().createCriteria(getEntityClass());
- criteria.add(Restrictions.eq(name, value));
- return criteria.list();
- }
-
-
-
-
- public List findByLike(String name, String value) {
- Assert.hasText(name);
- Criteria criteria = getSession().createCriteria(getEntityClass());
- criteria.add(Restrictions.like(name, value, MatchMode.ANYWHERE));
- return criteria.list();
- }
-
-
-
-
-
-
-
- public List findBy(Map filter, CriteriaSetup criteriaSetup) {
- Criteria criteria = getEntityCriteria();
- if (!CollectionUtils.isEmpty(filter)) {
- criteriaSetup.setup(criteria, filter);
- }
- return criteria.list();
- }
-
-
-
-
-
- public List findBy(Map filter) {
- return findBy(filter, getDefaultCriteriaSetup());
- }
-
- protected CriteriaSetup getDefaultCriteriaSetup() {
- return new CriteriaSetup() {
- public void setup(Criteria criteria, Map filter) {
- if (filter != null && !filter.isEmpty()) {
- Set keys = filter.keySet();
- for (Object key : keys) {
- String value = (String) filter.get(key);
- if (StringUtils.isNotBlank(value))
- criteria.add(Restrictions.eq((String) key, value));
- }
- }
- }
- };
- }
-
-
-
-
- protected Criteria getEntityCriteria() {
- return getSession().createCriteria(getEntityClass());
- }
-
-
-
-
-
-
-
-
- protected void sortCriteria(Criteria criteria, Map sortMap, Object entity) {
- if (!sortMap.isEmpty()) {
- for (Object o : sortMap.keySet()) {
- String fieldName = o.toString();
- String orderType = sortMap.get(fieldName).toString();
-
-
- if (fieldName.indexOf('.') != -1) {
- String alias = StringUtils.substringBefore(fieldName, ".");
- String aliasType = alias;
- try {
- aliasType = PropertyUtils.getProperty(entity, alias).getClass().getSimpleName();
- } catch (Exception e) {
- logger.error("Get property" + alias + " error");
- }
- criteria.createAlias(aliasType, alias);
- }
-
- if ("asc".equalsIgnoreCase(orderType)) {
- criteria.addOrder(Order.asc(fieldName));
- } else {
- criteria.addOrder(Order.desc(fieldName));
- }
- }
- }
- }
-
-
-
-
-
-
-
- public boolean isNotUnique(Object entity, String names) {
- Assert.hasText(names);
- Criteria criteria = getSession().createCriteria(entity.getClass()).setProjection(Projections.rowCount());
- String[] nameList = names.split(",");
- try {
- for (String name : nameList) {
- criteria.add(Restrictions.eq(name, PropertyUtils.getProperty(entity, name)));
- }
-
- String keyName = getSessionFactory().getClassMetadata(entity.getClass()).getIdentifierPropertyName();
- if (keyName != null) {
- Object id = PropertyUtils.getProperty(entity, keyName);
-
- if (id != null)
- criteria.add(Restrictions.not(Restrictions.eq(keyName, id)));
- }
- }
- catch (Exception e) {
- logger.error(e.getMessage());
- return false;
- }
- return ((Integer) criteria.uniqueResult()) > 0;
- }
- }
posted on 2007-02-07 08:45
☜♥☞MengChuChen 阅读(2200)
评论(3) 编辑 收藏 所属分类:
hibernate