SPRING-DATA-JPA 全局DAO配置



配置文件:spring-jpa.xml

[html] view plain copy
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:c="http://www.springframework.org/schema/c" xmlns:util="http://www.springframework.org/schema/util"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:jpa="http://www.springframework.org/schema/data/jpa"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  9.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd  
  10.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
  11.         http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd  
  12.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">  
  13.   
  14.       
  15.   
  16.       
  17.       
  18.     <bean id="entityManagerFactory"  
  19.         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
  20.         <property name="dataSource" ref="${springJPA.dataSource}" />  
  21.         <property name="persistenceProvider" ref="persistenceProvider" />  
  22.         <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />  
  23.         <property name="jpaDialect" ref="jpaDialect" />  
  24.         <property name="packagesToScan" value="${springJPA.packagesToScan}" />  
  25.         <property name="jpaProperties">  
  26.             <props>  
  27.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialectprop>  
  28.                 <prop key="hibernate.connection.driver_class">oracle.jdbc.OracleDriverprop>  
  29.                 <prop key="hibernate.max_fetch_depth">3prop>  
  30.                 <prop key="hibernate.jdbc.fetch_size">18prop>  
  31.                 <prop key="hibernate.jdbc.batch_size">10prop>  
  32.                 <prop key="hibernate.hbm2ddl.auto">${springJPA.jpaProperties.hibernate.hbm2ddl.auto}prop>  
  33.                 <prop key="hibernate.show_sql">falseprop>  
  34.                 <prop key="hibernate.format_sql">falseprop>  
  35.                 <prop key="javax.persistence.validation.mode">noneprop>  
  36.                   
  37.                 <prop key="hibernate.cache.use_query_cache">trueprop>   
  38.                 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactoryprop>  
  39.                   
  40.                 <prop key="javax.persistence.sharedCache.mode">ENABLE_SELECTIVEprop>  
  41.                 <prop key="hibernate.generate_statistics">trueprop>  
  42.             props>  
  43.         property>  
  44.     bean>  
  45.   
  46.       
  47.       
  48.     <bean id="persistenceProvider" class="org.hibernate.ejb.HibernatePersistence" />  
  49.       
  50.       
  51.     <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
  52.         <property name="database" value="${springJPA.jpaVendorAdapter.database}" />  
  53.     bean>  
  54.       
  55.       
  56.     <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />  
  57.       
  58.       
  59.     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">  
  60.         <property name="entityManagerFactory" ref="entityManagerFactory" />  
  61.     bean>  
  62.   
  63.   
  64.       
  65.       
  66.     <tx:annotation-driven />  
  67.   
  68.       
  69.     <jpa:repositories base-package="com.wonders.**.dao"  
  70.         entity-manager-factory-ref="entityManagerFactory"  
  71.         transaction-manager-ref="transactionManager"  
  72.         repository-impl-postfix="Impl"  
  73.         factory-class="com.wonders.frame.core.dao.DefaultRepositoryFactoryBean">  
  74.     jpa:repositories>  
  75.   
  76.   
  77. beans>  

工厂bean:DefaultRepositoryFactoryBean

[java] view plain copy
  1. /** 
  2.  *  
  3.  */  
  4. package com.wonders.frame.core.dao;  
  5. import java.io.Serializable;  
  6. import javax.persistence.EntityManager;  
  7.   
  8. import org.springframework.data.jpa.repository.JpaRepository;  
  9. import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;  
  10. import org.springframework.data.repository.core.support.RepositoryFactorySupport;  
  11.   
  12. /** 
  13.  * 
  14.  * 
  15.  */  
  16. public class DefaultRepositoryFactoryBeanextends JpaRepository, S, ID extends Serializable>  
  17.         extends JpaRepositoryFactoryBean {  
  18.     /** 
  19.      * Returns a {@link RepositoryFactorySupport}. 
  20.      * 
  21.      * @param entityManager 
  22.      * @return 
  23.      */  
  24.     protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {  
  25.    
  26.         return new DefaultRepositoryFactory(entityManager);  
  27.     }  
  28. }  

工厂类:DefaultRepositoryFactory

[java] view plain copy
  1. package com.wonders.frame.core.dao;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.EntityManager;  
  6.   
  7. import org.springframework.data.jpa.repository.JpaRepository;  
  8. import org.springframework.data.jpa.repository.support.JpaEntityInformation;  
  9. import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;  
  10. import org.springframework.data.querydsl.QueryDslPredicateExecutor;  
  11. import org.springframework.data.querydsl.QueryDslUtils;  
  12. import org.springframework.data.repository.core.RepositoryMetadata;  
  13. import org.springframework.util.Assert;  
  14.   
  15. import com.wonders.frame.core.dao.impl.GenericRepositoryImpl;  
  16.   
  17. /** 
  18.  *  
  19.  * 
  20.  */  
  21. public class DefaultRepositoryFactory extends JpaRepositoryFactory {  
  22.   
  23.     private final EntityManager entityManager;  
  24.       
  25.     public DefaultRepositoryFactory(EntityManager entityManager) {  
  26.         super(entityManager);  
  27.         Assert.notNull(entityManager);  
  28.         this.entityManager = entityManager;  
  29.           
  30.     }  
  31.       
  32.     @Override  
  33.     protected extends Serializable> JpaRepository getTargetRepository(RepositoryMetadata metadata, EntityManager entityManager) {  
  34.   
  35.         //TODO  
  36.         JpaEntityInformation entityInformation = getEntityInformation(metadata.getDomainClass());  
  37.         return new GenericRepositoryImpl(entityInformation, entityManager); // custom implementation  
  38.     }  
  39.     
  40.     @Override  
  41.     protected Class getRepositoryBaseClass(RepositoryMetadata metadata) {  
  42.    
  43.         return GenericRepositoryImpl.class;  
  44.     }  
  45. }  

自定义扩展接口:GenericRepository

[java] view plain copy
  1. package com.wonders.frame.core.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashMap;  
  5. import java.util.LinkedHashMap;  
  6. import java.util.List;  
  7.   
  8. import javax.persistence.Query;  
  9.   
  10. import org.springframework.data.domain.Pageable;  
  11. import org.springframework.data.jpa.repository.JpaRepository;  
  12. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;  
  13. import org.springframework.data.repository.CrudRepository;  
  14. import org.springframework.data.repository.NoRepositoryBean;  
  15. import org.springframework.transaction.annotation.Transactional;  
  16.   
  17. import com.wonders.frame.core.model.vo.SimplePage;  
  18.   
  19.   
  20.   
  21. /** 
  22.  
  23.  * @ 
  24.  
  25.  * 针对spring data jpa所提供的接口{@link JpaRepository}再次扩展 
  26.  
  27.  * @NoRepositoryBean是必须的 
  28.  
  29.  */  
  30.   
  31. @NoRepositoryBean  
  32. public interface GenericRepositoryextends Serializable>   
  33.     extends JpaRepository,JpaSpecificationExecutor {  
  34.       
  35.     List findAll(HashMap queryParams,  
  36.             LinkedHashMap orderby);  
  37.   
  38.   
  39.     SimplePage findByPage(HashMap queryParams,  
  40.             LinkedHashMap orderby, Integer pageSize,Integer pageNum);  
  41.       
  42.     SimplePage findByPageWithSql(String sql,  
  43.             HashMap queryParams, Integer pageSize,  
  44.             Integer pageNum);  
  45.   
  46.     SimplePage findByPageWithWhereHql(String whereHql,  
  47.             HashMap queryParams, Integer pageSize,  
  48.             Integer pageNum);  
  49.   
  50.   
  51.     SimplePage findByPage(HashMap queryParams,  
  52.             String orderby, Integer pageSize, Integer pageNum);  
  53.   
  54.     /** 
  55.      *  
  56.      * 根据sql语句查询,结果是实体的集合 
  57.      *  
  58.      * @param sql 
  59.      *  
  60.      * @param entityClass 
  61.      *  
  62.      * @return 
  63.      */  
  64.   
  65.     public List findAllBySql(Class entityClass, String sql);  
  66.       
  67.     public String getUniqueResultBySql(String sql,HashMap queryParams);  
  68.       
  69.     //public List findByAttachIds(String[] ids);  
  70.       
  71. //  @Transactional  
  72. //  public void updateModelNameAndModelId(String modelName, Integer modelId, String[] ids);  
  73. }  


自定义扩展实现类:GenericRepositoryImpl ,其中的其他方法都是全局共享方法,即每个继承自定义扩展接口的用户接口均可使用这些函数

[java] view plain copy
  1. package com.wonders.frame.core.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashMap;  
  5. import java.util.LinkedHashMap;  
  6. import java.util.List;  
  7.   
  8. import javax.persistence.EntityManager;  
  9. import javax.persistence.Query;  
  10.   
  11. import org.apache.log4j.Logger;  
  12. import org.springframework.data.jpa.repository.support.JpaEntityInformation;  
  13. import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport;  
  14. import org.springframework.data.jpa.repository.support.SimpleJpaRepository;  
  15. import org.springframework.data.repository.NoRepositoryBean;  
  16. import org.springframework.data.repository.query.Param;  
  17. import org.springframework.transaction.annotation.Transactional;  
  18.   
  19. import com.wonders.frame.core.dao.GenericRepository;  
  20. import com.wonders.frame.core.model.vo.PageInfo;  
  21. import com.wonders.frame.core.model.vo.SimplePage;  
  22. import com.wonders.frame.core.utils.ReflectUtil;  
  23.   
  24.   
  25.   
  26. /** 
  27.  * {@link GenericRepository}接口实现类,并在{@link SimpleJpaRepository}基础上扩展。 
  28.  * @param  ORM对象 
  29.  * @param  主键ID    
  30.  */  
  31. @NoRepositoryBean   // 必须的  
  32. public class GenericRepositoryImplextends Serializable> extends  
  33.         SimpleJpaRepository implements GenericRepository {  
  34.   
  35.     static Logger logger = Logger.getLogger(GenericRepositoryImpl.class);  
  36.     private final EntityManager em;  
  37.     private final Class entityClass;  
  38.     private final String entityName;  
  39.       
  40.   
  41.     /** 
  42.      * 构造函数 
  43.      * @param domainClass 
  44.      * @param em 
  45.      */  
  46.     public GenericRepositoryImpl(final JpaEntityInformation entityInformation, EntityManager entityManager) {  
  47.           
  48.         super(entityInformation, entityManager);  
  49.         this.em = entityManager;  
  50.         this.entityClass=entityInformation.getJavaType();  
  51.         this.entityName=entityInformation.getEntityName();  
  52.     }  
  53.       
  54.     /** 
  55.      * 构造函数 
  56.      * @param domainClass 
  57.      * @param em 
  58.      */  
  59.     public GenericRepositoryImpl(Class domainClass, EntityManager em) {  
  60.         this(JpaEntityInformationSupport.getMetadata(domainClass, em), em);   
  61.     }  
  62.       
  63.     @Override  
  64.     public List findAll(HashMap queryParams,  
  65.             LinkedHashMap orderby){          
  66.            
  67.         String whereHql=buildWhereQuery(queryParams);  
  68.         String orderHql=buildOrderby(orderby);  
  69.       
  70.         String hql = "select o from "+entityName+" o where o.removed=0";   
  71.         Query query=createQuery(hql+whereHql+orderHql,queryParams);  
  72.   
  73.         List list=(List)query.getResultList();  
  74.         return list;      
  75.     }  
  76.       
  77.       
  78.     @Override  
  79.     public SimplePage findByPage(HashMap queryParams,  
  80.             LinkedHashMap orderby, Integer pageSize,Integer pageNum) {  
  81.           
  82.         return findByPage(queryParams,buildOrderby(orderby), pageSize, pageNum);  
  83.   
  84.     }  
  85.     @Override  
  86.     public SimplePage findByPage(HashMap queryParams,  
  87.             String orderby, Integer pageSize,Integer pageNum) {  
  88.                        
  89.         String whereHql=buildWhereQuery(queryParams);  
  90.         String orderHql=orderby;  
  91.           
  92.         String hql="select count(*) from "+ entityName+ " o where o.removed=0 ";   
  93.         Query query=createQuery(hql+whereHql+orderHql,queryParams);  
  94.         PageInfo pageInfo=new PageInfo(((Long)query.getSingleResult()).intValue(),pageSize);  
  95.         pageInfo.refresh(pageNum);  
  96.           
  97.   
  98.         hql = "select o from "+ entityName+ " o where o.removed=0 ";  
  99.         query=createQuery(hql+whereHql+orderHql,queryParams);  
  100.         query.setFirstResult(pageInfo.getStartRecord()).setMaxResults(pageInfo.getPageSize());    
  101.   
  102.         return new SimplePage(pageInfo,query.getResultList());  
  103.     }  
  104.       
  105.     private Query createQuery(String hql,HashMap queryParams){  
  106.         Query query = em.createQuery(hql);  
  107.         setQueryParams(query, queryParams);  
  108.         return query;  
  109.     }  
  110.     @Override  
  111.     public SimplePage findByPageWithWhereHql(String whereHql, HashMap queryParams, Integer pageSize,Integer pageNum) {  
  112.           
  113.         String hql="select count(*) from "+ entityName+ " o where o.removed=0 ";    
  114.         if(whereHql==null){  
  115.             whereHql="";  
  116.         }  
  117.   
  118.         Query query = em.createQuery(hql+whereHql);  
  119.         setQueryParams(query, queryParams);  
  120.         PageInfo pageInfo=new PageInfo(((Long)query.getSingleResult()).intValue(),pageSize);  
  121.         pageInfo.refresh(pageNum);  
  122.           
  123.   
  124.         hql = "select o from "+ entityName+ " o where o.removed=0 ";  
  125.         query = em.createQuery(hql+whereHql);          
  126.         setQueryParams(query, queryParams);  
  127.         query.setFirstResult(pageInfo.getStartRecord()).setMaxResults(pageInfo.getPageSize());    
  128.   
  129.         return new SimplePage(pageInfo,query.getResultList());  
  130.     }  
  131.       
  132.     @Override  
  133.     public SimplePage findByPageWithSql(String sql, HashMap queryParams, Integer pageSize,Integer pageNum) {  
  134.   
  135.         Query query = em.createNativeQuery("select count(*) from ("+sql+")");    
  136.         setQueryParams(query, queryParams);  
  137.           
  138.         PageInfo pageInfo=new PageInfo(((Long)query.getSingleResult()).intValue(),pageSize);  
  139.         pageInfo.refresh(pageNum);  
  140.           
  141.         query = em.createNativeQuery(sql);  
  142.         setQueryParams(query, queryParams);  
  143.         query.setFirstResult(pageInfo.getStartRecord()).setMaxResults(pageInfo.getPageSize());    
  144.   
  145.         return new SimplePage(pageInfo,query.getResultList());  
  146.     }  
  147.       
  148.     private void setQueryParams(Query query, HashMap queryParams){  
  149.         if(queryParams!=null && queryParams.size()>0){  
  150.             for(String key : queryParams.keySet()){  
  151.                 Class clazz=ReflectUtil.getFieldType(this.entityClass, key.replaceAll("_s","").replaceAll("_e""").replaceAll("_in"""));  
  152.                 if(clazz!=null && clazz.equals(String.class) && !key.endsWith("_in")){  
  153.                     query.setParameter(key, '%'+queryParams.get(key).toString()+'%');  
  154.                 }else{  
  155.                     query.setParameter(key, queryParams.get(key));  
  156.                 }  
  157.   
  158.             }  
  159.         }  
  160.     }  
  161.   
  162.     private String buildOrderby(LinkedHashMap orderby) {  
  163.         // TODO Auto-generated method stub  
  164.         StringBuffer orderbyql = new StringBuffer("");  
  165.         if(orderby!=null && orderby.size()>0){  
  166.             orderbyql.append(" order by ");  
  167.             for(String key : orderby.keySet()){  
  168.                 orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");  
  169.             }  
  170.             orderbyql.deleteCharAt(orderbyql.length()-1);  
  171.         }  
  172.           
  173.         return orderbyql.toString();  
  174.     }  
  175.       
  176.     private String buildWhereQuery(HashMap queryParams) {  
  177.         // TODO Auto-generated method stub  
  178.         StringBuffer whereQueryHql = new StringBuffer("");  
  179.         if(queryParams!=null && queryParams.size()>0){  
  180.             for(String key : queryParams.keySet()){  
  181. //              if(key.equalsIgnoreCase("id")){  
  182. //                  whereQueryHql.append(" and ").append("o.").append(key).append(" in(:").append(key).append(")");  
  183. //              }else   
  184.                 if(key.endsWith("_s")){  
  185.                     whereQueryHql.append(" and ").append("o.").append(key.replace("_s""")).append(" >=:").append(key);  
  186.                 }else if(key.endsWith("_e")){  
  187.                     whereQueryHql.append(" and ").append("o.").append(key.replace("_e""")).append(" <=:").append(key);  
  188.                 }else if(key.endsWith("_in")){  
  189.                     whereQueryHql.append(" and ").append("o.").append(key.replace("_in""")).append(" in:").append(key);  
  190.                 }else{  
  191.                     Class clazz=ReflectUtil.getFieldType(this.entityClass, key);  
  192.                     if(clazz!=null && clazz.equals(String.class)){  
  193.                         whereQueryHql.append(" and ").append("o.").append(key).append(" like :").append(key);  
  194.                     }else{  
  195.                         whereQueryHql.append(" and ").append("o.").append(key).append(" =:").append(key);  
  196.                     }  
  197.                       
  198.                 }  
  199.             }  
  200.         }  
  201.           
  202.         return whereQueryHql.toString();  
  203.     }  
  204.   
  205.     @Override  
  206.     public List findAllBySql(Class entityClass, String sql) {  
  207.           //创建原生SQL查询QUERY实例,指定了返回的实体类型  
  208.           Query query =  em.createNativeQuery(sql,entityClass);  
  209.           //执行查询,返回的是实体列表,  
  210.           List EntityList = query.getResultList();  
  211.         return EntityList;  
  212.     }  
  213.   
  214.     public String getUniqueResultBySql(String sql,HashMap queryParams){  
  215.         Query query =  em.createNativeQuery(sql);  
  216.         for(String key : queryParams.keySet()){  
  217.             query.setParameter(key, queryParams.get(key));  
  218.         }  
  219.         //执行查询,返回的是实体列表,  
  220.         String result = (String)query.getSingleResult();  
  221.        return result;  
  222.     }  
  223.   
  224. //  public List findByAttachIds(String[] ids){  
  225. //      String idsString ="";  
  226. //      if(ids==null || ids.length<1) return null;  
  227. //      for(int i=0; i  
  228. //          try {  
  229. //              Long.valueOf(ids[i]);  
  230. //          } catch (NumberFormatException e) {  
  231. //              return null;  
  232. //          }  
  233. //          idsString += ids[i] +",";  
  234. //      }  
  235. //      idsString = idsString.substring(0,idsString.length()-1);  
  236. //      String hql ="from Attach t where t.removed='0' and t.id in ("+idsString+")";  
  237. //      Query query=createQuery(hql, null);  
  238. //      List list=(List)query.getResultList();  
  239. //      return list;      
  240. //  }  
  241. //    
  242. //  @Transactional  
  243. //  public void updateModelNameAndModelId(String modelName, Integer modelId, String[] ids){  
  244. //      String idsString ="";  
  245. //      if(ids==null || ids.length<1) return;  
  246. //      for(int i=0; i  
  247. //          try {  
  248. //              Long.valueOf(ids[i]);  
  249. //          } catch (NumberFormatException e) {  
  250. //              return;  
  251. //          }  
  252. //          idsString += ids[i] +",";  
  253. //      }  
  254. //      idsString = idsString.substring(0,idsString.length()-1);  
  255. //      String hql ="update Attach a set a.modelName ="+modelName+", a.modelId ="+modelId+" where a.id in ("+idsString+")";  
  256. //      createQuery(hql, null).executeUpdate();  
  257. //  }  
  258.   
  259. }  

使用范例:自定义接口继承 扩展接口

[java] view plain copy
  1. package com.wonders.frame.cpq.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.persistence.QueryHint;  
  6.   
  7. import org.springframework.data.domain.Page;  
  8. import org.springframework.data.domain.Pageable;  
  9. import org.springframework.data.jpa.repository.Modifying;  
  10. import org.springframework.data.jpa.repository.Query;  
  11. import org.springframework.data.jpa.repository.QueryHints;  
  12. import org.springframework.data.repository.query.Param;  
  13. import org.springframework.transaction.annotation.Transactional;  
  14.   
  15. import com.wonders.frame.core.dao.GenericRepository;  
  16. import com.wonders.frame.cpq.model.bo.CpqMain;  
  17.   
  18. public interface CpqMainDao extends GenericRepository{  
  19.   
  20.     public Page findAll(Pageable pageable);  
  21.           
  22.     @Query("select a from CpqMain a where a.removed = 0 and a.id =?")  
  23.     public CpqMain findById(Integer id);  
  24.       
  25.     @Transactional    
  26.     @Modifying   
  27.     @Query("update CpqMain a set a.removed = 1 where a.id =:id")  
  28.     public Integer removeById(@Param("id")Integer id);  
  29.       
  30.       
  31.     @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })    
  32.     public List findAll();    
  33.   
  34.       

你可能感兴趣的:(微服务)