gaolixu 发表于 2013-2-4 22:21:03

GenericSpringDAO<T extends ...>

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.AbstractQueryImpl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
 
 
 
@Repository
public class GenericSpringDAO<T extends AbstractPersistentVO>
 extends HibernateDaoSupport
  implements GenericDAOIF<T> {
 
 /**
  * Definite Logger
  */
 private static final Logger LOGGER = Logger.getLogger(GenericSpringDAO.class.getName());
 
 /**
  * Definite template class
  */
 private Class<T> persistentClass;
 
    /**
     *  Default constructor of GenericSpringDAO
     */
 public GenericSpringDAO(){
  super();
 }
 
 /**
  * constructor
  * @param sessionFactory sessionFactory
  */
 @SuppressWarnings("unchecked")
 public GenericSpringDAO(SessionFactory sessionFactory){
  this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
  setSessionFactory(sessionFactory);
 }
 public Class<T> getPersistentClass(){
  return persistentClass;
 }
 
 /**
  * findById method
  * @param id id
   */
 @SuppressWarnings("unchecked")
 public T findById(Serializable id){
  T t = (T) getSession().get(getPersistentClass(), id);
  LOGGER.info("Find by ID for " + getPersistentClass().getSimpleName() + ", using id = '" + id + "', returning: " + ((t==null)?null:t.toString()));
  
  return t;
 }
 /**
  * findAll 
  */
 public List<T> findAll(){
  LOGGER.info("Find all for " + getPersistentClass().getSimpleName() + ".");
  List<T> list = findByCriteria();
  logListResults("Find all", list);
  return list;
 }

 /**
  * findByExample
  * @param exampleInstance exampleInstance
  * @param excludeProperty excludeProperty
  * @return list
  */
 @SuppressWarnings("unchecked")
 public final List<T> findByExample(T exampleInstance, String... excludeProperty)
 {
  Criteria c = prepareExampleCriteria(exampleInstance, excludeProperty);
  LOGGER.info("Find by example for " + getPersistentClass().getSimpleName() + ", using criteria = " + c.toString() + ".");
  List<T> list = c.list();
  logListResults("Find by example", list);
  return list;
 }
 
 /**
  * findByExample
  * @param exampleInstance exampleInstance
  * @param criterion criterion
  * @param excludeProperty excludeProperty
  * @return list
  */
 @SuppressWarnings("unchecked")
 public final List<T> findByExample(T exampleInstance,Criterion criterion , String... excludeProperty)
 {
  Criteria c = prepareExampleCriteria(exampleInstance, excludeProperty);
  c.add(criterion);
  LOGGER.info("Find by example for " + getPersistentClass().getSimpleName() + ", using criteria = " + c.toString() + ".");
  List<T> list = c.list();
  logListResults("Find by example", list);
  return list;
 }
 /**
  * findUniqueByExample
  * @param exampleInstance exampleInstance
  * @param excludeProperty excludeProperty
  * @return t
  */
 @SuppressWarnings("unchecked")
 public T findUniqueByExample(T exampleInstance, String... excludeProperty){
  Criteria c = prepareExampleCriteria(exampleInstance, excludeProperty);
  LOGGER.info("Find Unique by example for " + getPersistentClass().getSimpleName() + ", using criteria = " + c.toString() + ".");
  T t = (T)c.uniqueResult();
  LOGGER.info("Find Unique by example for " + getPersistentClass().getSimpleName() + ", using example = " + exampleInstance + ", returning: " + ((t==null)?null:t.toString()));
  return t;
 }
 /**
  * findUniqueByExample
  * @param query sql query
  * @return list
  */
 @SuppressWarnings("unchecked")
 protected final List<T> executeQueryList(SQLQuery query){
  StringBuilder params = new StringBuilder();
  if (query instanceof AbstractQueryImpl){
   params.append(", using params = ");
   Object[] values = ((AbstractQueryImpl)query).getQueryParameters(null).getPositionalParameterValues();
   for (int i = 0; i < values.length; i++){
    if (i!=0){
     params.append(", ");
    }
    params.append(values.toString());
   }
  }
  LOGGER.info("Execute Query for " + getPersistentClass().getSimpleName() + ", using query = " + query.getQueryString() + params.toString() + ".");
  List<T> result =  query.list();
  logListResults("Execute Query", result);
  return result;
 }
 /**
  * executeQuery
  * @param criteria criteria
  * @return list
  */
 @SuppressWarnings("unchecked")
 protected final List<T> executeQuery(Criteria criteria){
  LOGGER.info("Execute Query for " + getPersistentClass().getSimpleName() + ", using criteria = " + criteria.toString() + ".");
  List<T> result =  criteria.list();
  logListResults("Execute Query", result);
  return result;
 }
 
 /**
  * prepareBlankCriteria
  * @return criteria
  */
 protected Criteria prepareBlankCriteria(){
  Criteria crit = getSession().createCriteria(getPersistentClass());
  return crit;
 }
 
 /**
  * injectFindByExampleExcludes
  * @param vo vo
  * @return string[]
  */
 protected String[] injectFindByExampleExcludes(T vo){
  //override in subclass as needed
  return null;
 }
 
 /**
  * injectFindByExampleCriteria
  * @param criteria criteria
  * @param vo vo
  */
 protected void injectFindByExampleCriteria(Criteria criteria, T vo){
  //override in subclass as needed
 }
 
 /**
  * prepareExampleCriteria
  * @param exampleInstance exampleInstance
  * @param excludeProperty excludeProperty
  * @return criteria
  */
 protected Criteria prepareExampleCriteria(T exampleInstance, String... excludeProperty){
  String[] excludes = injectFindByExampleExcludes(exampleInstance);
  if (excludes != null){
   List<String> excludeList = new ArrayList<String>(Arrays.asList(excludes));
   if (excludeProperty != null){
    Collections.addAll(excludeList, excludeProperty);
   }
   excludeProperty = new String;
   excludeProperty = excludeList.toArray(excludeProperty);
  }
  Criteria crit = prepareBlankCriteria();
  Example example = Example.create(exampleInstance);
  for (String exclude : excludeProperty){
   example.excludeProperty(exclude);
  }
  crit.add(example);
  crit.setMaxResults(1000);
  injectFindByExampleCriteria(crit, exampleInstance);
  return crit;
 }
 
 /**
  *
  * @param c criteria
  * @param propertyName property name
  * @param startDate start date
  * @param endDate end date
  * @return The criteria to allow call chaining
  */
 protected Criteria addDateRangeCriteria(Criteria c, String propertyName, Date startDate, Date endDate){
  c.add(Restrictions.ge(propertyName, startDate));
  c.add(Restrictions.le(propertyName, endDate));
  return c;
 }
 /**
  * Use this inside subclasses as a convenience method.
  * @param criterion criterion
  * @return list
  */
 @SuppressWarnings("unchecked")
 protected List<T> findByCriteria(Criterion... criterion){
  Criteria crit = getSession().createCriteria(getPersistentClass());
  for (Criterion c : criterion){
   crit.add(c);
  }
  return crit.list();
 } 
 
 /**
  * create
  * @param entity entity
  * @return entity
  */
 public T create(T entity){
  LOGGER.info("Create for " + getPersistentClass().getSimpleName() + ", using entity = " + entity + ".");
  getSession().save(entity);
  LOGGER.info("Create for " + getPersistentClass().getSimpleName() + ", returning = " + entity + ".");
  return entity;
 }
 
 /**
  * Persist
  * @param entity entity
  * @return entity
  */
 public T persist(T entity){
  LOGGER.info("Persist for " + getPersistentClass().getSimpleName() + ", using entity = " + entity + ".");
  getSession().persist(entity);
  LOGGER.info("Persist for " + getPersistentClass().getSimpleName() + ", returning = " + entity + ".");
  return entity;
 }
 /**
  * update method
  * @param entity entity
  * @return entity
  */
 @SuppressWarnings("unchecked")
 public T update(T entity){
  LOGGER.info("Update for " + getPersistentClass().getSimpleName() + ", using entity = " + entity + ".");
  if (!getSession().contains(entity)){
   entity = (T)getSession().merge(entity);
  }
  else{
   getSession().update(entity);
  }
  LOGGER.info("Update for " + getPersistentClass().getSimpleName() + ", returning = " + entity + ".");
  return entity;
 }
 
 /**
  * delete method
  * @param entity entity
  */
 public void delete(T entity){
  LOGGER.info("Delete for " + getPersistentClass().getSimpleName() + ", using entity = " + entity + ".");
  getSession().delete(entity);
 }
 /**
  * detach
  * @param entity entity
  */
 public void detach(T entity){
  LOGGER.info("Detaching entity : " + entity + ".");
  getSession().evict(entity);
 }
 /**
  * logListResults
  * @param methodName method name
  * @param list log list
  */
 private void logListResults(String methodName, List<T> list){
  //String lineSep = AbstractInitializer.getInitializer().getLineSep();
  String lineSep = "/";
  List<T> logList = null;
  String debugMsg = "";
  if (!LOGGER.isDebugEnabled() && list.size() > 10){
   logList = list.subList(0, 10);
   debugMsg = "  Only logging first 10 records.";
  }
  else{
   logList = list;
  }
  StringBuffer sb = new StringBuffer(logList.size() * 100);
  sb.append(debugMsg);
  for (T t : logList){
   sb.append(lineSep);
   sb.append(t.toString());
  }
  
  LOGGER.info(methodName + " for " + getPersistentClass().getSimpleName() + ", returning " + list.size() + " records." + sb.toString());
 } 
 
}
 
 
Daoimpl:
........
 
/**
  * injectFindByExampleCriteria
  * @param criteria criteria
  * @param countryLanguageVO CountryLanguageVO
  */
 @Override
 public void injectFindByExampleCriteria(Criteria criteria,
   CountryLanguageVO countryLanguageVO) {
  if (null != countryLanguageVO.getCountryVO()) {
   if (null != countryLanguageVO.getCountryVO().getCountryId()) {
    criteria.add(Restrictions.eq("countryVO", countryLanguageVO
      .getCountryVO()));
   }
   else {
    Example example = Example.create(countryLanguageVO
      .getCountryVO());
    criteria.createCriteria("countryVO").add(example);
   }
  }
  if (null != countryLanguageVO.getLanguageVO()) {
   if (null != countryLanguageVO.getLanguageVO().getLanguageCd()) {
    criteria.add(Restrictions.eq("languageVO", countryLanguageVO
      .getLanguageVO()));
   }
   else {
    Example example = Example.create(countryLanguageVO
      .getLanguageVO());
    criteria.createCriteria("languageVO").add(example);
   }
  }
 }
 
 
页: [1]
查看完整版本: GenericSpringDAO<T extends ...>