`

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()[0];
  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[i].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[excludeList.size()];
   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);
   }
  }
 }

 

 

分享到:
评论

相关推荐

    Java中List<? extends T>与List<? super T>的区别(值得珍藏)

    extends T&gt;和List&lt;? super T&gt;是泛型的不同使用形式,它们在类型约束和操作上有所不同。 1. List&lt;? extends T&gt; - `? extends T` 是类型上界的表示,意味着列表中的元素可以是T类型或者是T的任何子类型。这种类型的...

    Visual C++ 编程资源大全(英文源码 其它)

    1,01.zip&lt;br&gt;Output&lt;br&gt;显示所有的调试信息(5KB)&lt;END&gt;&lt;br&gt;2,02.zip&lt;br&gt;Some general debugging tips&lt;br&gt;一般的调试技巧(11KB)&lt;END&gt;&lt;br&gt;3,03.zip&lt;br&gt;Debugging ISAPI extension&lt;br&gt;调试ISAPI扩展(4KB)&lt;END&gt;&lt;br&gt;4,04....

    Java测试题2答案

    &lt;br&gt; }&lt;br&gt;}&lt;br&gt;&lt;br&gt;答案::填空第1题&lt;br&gt;x=10,a=3,b=4,c=5&lt;br&gt;填空第2题&lt;br&gt;java.util&lt;br&gt;填空第3题&lt;br&gt;(public )(static )(void)(main)(String args[])&lt;br&gt;填空第4题&lt;br&gt;1&lt;br&gt;填空第5题&lt;br&gt;

    自定义拦截器struts2源代码

    &lt;package name="default" namespace="/" extends="struts-default"&gt; ... &lt;action name="myAction" class="com.example.MyAction"&gt; &lt;interceptor-ref name="myStack"/&gt; &lt;result&gt;success.jsp&lt;/result&gt; &lt;/action&gt;...

    程序设计基础答案

    〖程序设计基础〗练习题1&lt;br&gt;一、选择题(每题1分,共30分)&lt;br&gt;...&lt;br&gt;public class myprogram extends _______//定义小程序的主类&lt;br&gt;{&lt;br&gt;Label p1;&lt;br&gt;TextField in;&lt;br&gt;public void init()&lt;br&gt;{ p1=new Label("请...

    Java学习题答案

    对象成员变量在对象创建时会获得一个缺省的初始值.&lt;br&gt;5.Java数组随时可以改变大小.&lt;br&gt;6.InputStream和OutputStream读写的数据是8位的.&lt;br&gt;7.Java是强类型语言.&lt;br&gt;8.Java没有指针,引用不能等同于...

    javaservlet连接mysql数据库.pdf

    &lt;value&gt;org.apache.commons.dbcp.BasicDataSourceFactory&lt;/value&gt; &lt;/parameter&gt; ... &lt;parameter&gt; &lt;name&gt;username&lt;/name&gt; &lt;value&gt;root&lt;/value&gt; &lt;/parameter&gt; &lt;parameter&gt; &lt;name&gt;password&lt;/name&gt; &lt;value&gt;...

    Spring/泛型Hibernate的实现

    public class HibernateDaoImpl&lt;T, PK extends Serializable&gt; implements IHibernateDao&lt;T, PK&gt; { private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate ...

    SSH整合实例,带图版

    &lt;package name="default" namespace="/" extends="struts-default"&gt; &lt;action name="myAction" class="com.example.MyAction"&gt; &lt;result name="success"&gt;/success.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; ... &lt;/...

    Struts2 配置第一个拦截器

    &lt;package name="default" extends="struts-default"&gt; &lt;action name="myAction" class="com.example.MyAction"&gt; &lt;interceptor-ref name="myStack"/&gt; &lt;result name="success"&gt;/success.jsp&lt;/result&gt; &lt;/action&gt; ...

    Spring Boot整合Shiro搭建权限管理系统 (2).docx

    Map&lt;String, String&gt; filterChainDefinitionMap = new HashMap&lt;&gt;(); // ... factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return factoryBean; } } @Configuration @...

    collections方法集合

    List&lt;String&gt; flavors = new ArrayList&lt;&gt;(); Collections.addAll(flavors, "Peaches'nPlutonium", "RockyRacoon"); ``` 此例中,`flavors`列表将被填充上指定的字符串元素。 #### 2. `asLifoQueue` 此方法将`...

    struts2实例 学生信息管理系统

    &lt;package name="Student_CRUD_DEMO" extends="struts-default" namespace="/jsp"&gt; &lt;action name="add" class="cn.fjnu.edu.action.AddAction" method="addStu"&gt; &lt;result name="success"&gt;list.jsp&lt;/result&gt; &lt;/...

    网站登录页面代码实例(JSP+Servlet+JavaBean)

    out.println("&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;hr&gt;&lt;center&gt;&lt;font color=red size=12&gt;&lt;B&gt;"); try...{ UserBean user=new UserBean(); if(user.check(name,pword)) out.println("登陆成功"); else out.println("登陆失败"); }...

    Cassandra单元测试CassandraUnit.zip

    &lt;keyspace &lt;name&gt;beautifulKeyspaceName&lt;/name&gt; &lt;columnFamilies&gt; &lt;columnFamily&gt; &lt;name&gt;beautifulColumnFamilyName&lt;/name&gt; &lt;row&gt; &lt;key&gt;key10&lt;/key&gt; &lt;column&gt; &lt;name&gt;name11&lt;/name&gt; &lt;value&gt;value11&lt;/value&gt; ...

    struts-2.3.4.1所需的jar文件

    接触新版本出了问题后,解决了把jar文件...&lt;package name="default" namespace="/" extends="struts-default"&gt; &lt;action name="helloworld"&gt; &lt;result&gt; /helloWorld.jsp &lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt;

    Spring4整合Jersey2.9

    &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;4.x.x.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;...

    Go语言模板引擎gotpl.zip

     &lt;p&gt;...&lt;/p&gt;  case 2:  &lt;p&gt;...&lt;/p&gt;  default:  &lt;p&gt;...&lt;/p&gt;  } }模板继承(extends,block)base.tpl :&lt;html&gt;@block aa {aaaa@block bb {bbb}@block cc {ccc} }@section Pagination(curPage int...

    structs2动态添加表单

    &lt;package name="erpweb" extends="struts-default"&gt; &lt;global-results&gt; &lt;result name="IOException" &gt;/error/ioexception.jsp&lt;/result&gt; &lt;result name="SQLException" &gt;/error/sqlexception.jsp&lt;/result&gt; &lt;/...

    SpringMVC4整合tiles3

    &lt;definition name="home" extends="baseLayout"&gt; &lt;put-attribute name="title" value="Home Page" /&gt; &lt;put-attribute name="page" value="/WEB-INF/views/home.jsp" /&gt; &lt;/definition&gt; &lt;!-- 更多页面定义... --...

Global site tag (gtag.js) - Google Analytics