Spring Data是一个非常方便的库。 但是,由于该项目是一个相当新的项目,因此功能不佳。 默认情况下,Spring Data JPA将基于SimpleJpaRepository提供DAO的实现。 在最近的项目中,我开发了一个定制的存储库基类,以便可以在其上添加更多功能。 您可以根据需要向该存储库基类添加特定于供应商的功能。

组态

您必须在spring bean配置文件中添加以下配置。 您必须指定一个新的存储库工厂类。 我们将在以后开发课程。

<jpa:repositories base-package='example.borislam.dao'
factory-class='example.borislam.data.springData.DefaultRepositoryFactoryBean/>

只需开发一个扩展JpaRepository的接口即可。 您应该记得用@NoRepositoryBean对其进行注释。

@NoRepositoryBean
public interface GenericRepository <T, ID extends Serializable> extends JpaRepository<T, ID> {
}

定义自定义存储库基础实现类

下一步是开发定制的基础存储库类。 您可以看到我只是这个自定义基础存储库中的一个属性(即springDataRepositoryInterface)。 我只想对存储库接口的自定义行为的行为进行更多控制。 在下一篇文章中,我将展示如何添加此基础存储库类的更多功能。

@SuppressWarnings('unchecked')
@NoRepositoryBean
public class GenericRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>  implements GenericRepository<T, ID> , Serializable{private static final long serialVersionUID = 1L;static Logger logger = Logger.getLogger(GenericRepositoryImpl.class);private final JpaEntityInformation<T, ?> entityInformation;private final EntityManager em;private final DefaultPersistenceProvider provider;private  Class<?> springDataRepositoryInterface; public Class<?> getSpringDataRepositoryInterface() {return springDataRepositoryInterface;}public void setSpringDataRepositoryInterface(Class<?> springDataRepositoryInterface) {this.springDataRepositoryInterface = springDataRepositoryInterface;}/*** Creates a new {@link SimpleJpaRepository} to manage objects of the given* {@link JpaEntityInformation}.* * @param entityInformation* @param entityManager*/public GenericRepositoryImpl (JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager , Class<?> springDataRepositoryInterface) {super(entityInformation, entityManager);this.entityInformation = entityInformation;this.em = entityManager;this.provider = DefaultPersistenceProvider.fromEntityManager(entityManager);this.springDataRepositoryInterface = springDataRepositoryInterface;}/*** Creates a new {@link SimpleJpaRepository} to manage objects of the given* domain type.* * @param domainClass* @param em*/public GenericRepositoryImpl(Class<T> domainClass, EntityManager em) {this(JpaEntityInformationSupport.getMetadata(domainClass, em), em, null);  }public <S extends T> S save(S entity){     if (this.entityInformation.isNew(entity)) {this.em.persist(entity);flush();return entity;}entity = this.em.merge(entity);flush();return entity;}public T saveWithoutFlush(T entity){return super.save(entity);}public List<T> saveWithoutFlush(Iterable<? extends T> entities){List<T> result = new ArrayList<T>();if (entities == null) {return result;}for (T entity : entities) {result.add(saveWithoutFlush(entity));}return result;}
}

作为一个简单的示例,我只是覆盖了SimpleJPARepository的默认保存方法。 持久保存后,save方法的默认行为不会刷新。 我进行了修改,以使其在持久化后保持刷新状态。 另一方面,我添加了另一个名为saveWithoutFlush()的方法,以允许开发人员调用保存实体而无需刷新。

定义自定义存储库工厂bean

最后一步是创建一个工厂bean类和一个工厂类,以根据您自定义的基本存储库类来生成存储库。

public class DefaultRepositoryFactoryBean <T extends JpaRepository<S, ID>, S, ID extends Serializable>extends JpaRepositoryFactoryBean<T, S, ID> {/*** Returns a {@link RepositoryFactorySupport}.* * @param entityManager* @return*/protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {return new DefaultRepositoryFactory(entityManager);}
}/*** * The purpose of this class is to override the default behaviour of the spring JpaRepositoryFactory class.* It will produce a GenericRepositoryImpl object instead of SimpleJpaRepository. * */
public  class DefaultRepositoryFactory extends JpaRepositoryFactory{private final EntityManager entityManager;private final QueryExtractor extractor;public DefaultRepositoryFactory(EntityManager entityManager) {super(entityManager);Assert.notNull(entityManager);this.entityManager = entityManager;this.extractor = DefaultPersistenceProvider.fromEntityManager(entityManager);}@SuppressWarnings({ 'unchecked', 'rawtypes' })protected <T, ID extends Serializable> JpaRepository<?, ?> getTargetRepository(RepositoryMetadata metadata, EntityManager entityManager) {Class<?> repositoryInterface = metadata.getRepositoryInterface();JpaEntityInformation<?, Serializable> entityInformation =getEntityInformation(metadata.getDomainType());if (isQueryDslExecutor(repositoryInterface)) {return new QueryDslJpaRepository(entityInformation, entityManager);} else {return new GenericRepositoryImpl(entityInformation, entityManager, repositoryInterface); //custom implementation}}@Overrideprotected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {if (isQueryDslExecutor(metadata.getRepositoryInterface())) {return QueryDslJpaRepository.class;} else {return GenericRepositoryImpl.class;}}/*** Returns whether the given repository interface requires a QueryDsl* specific implementation to be chosen.* * @param repositoryInterface* @return*/private boolean isQueryDslExecutor(Class<?> repositoryInterface) {return QUERY_DSL_PRESENT&& QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);}
}

结论

现在,您可以向基础存储库类添加更多功能。 在您的程序中,您现在可以创建自己的存储库接口,以扩展GenericRepository而不是JpaRepository。

public interface MyRepository <T, ID extends Serializable>extends GenericRepository <T, ID> {void someCustomMethod(ID id);
}

在下一篇文章中,我将向您展示如何向此GenericRepository添加休眠过滤器功能。

参考: “ 编程和平”博客上的JCG合作伙伴 Boris Lam 自定义Spring Data JPA存储库 。

翻译自: https://www.javacodegeeks.com/2012/08/customizing-spring-data-jpa-repository.html

自定义Spring Data JPA存储库相关推荐

  1. 定制Spring Data JPA存储库

    Spring Data是一个非常方便的库. 但是,由于该项目是一个相当新的项目,因此功能不佳. 默认情况下,Spring Data JPA将基于SimpleJpaRepository提供DAO的实现. ...

  2. 使用Spring Data REST将Spring Data JPA存储库导出为REST服务

    Spring Data模块提供了各种模块,以统一的方式处理各种类型的数据源,如RDBMS,NOSQL存储等. 在我以前的文章SpringMVC4 + Spring Data JPA +使用JavaCo ...

  3. Spring Data Redis存储库

    8. Redis存储库 使用Redis存储库允许在Redis哈希中无缝地转换和存储域对象,应用自定义映射策略并利用二级索引. Redis存储库至少需要Redis Server 2.8.0版. 8.1. ...

  4. springmvc jpa_使用JavaConfig的SpringMVC4 + Spring Data JPA + SpringSecurity配置

    springmvc jpa 在本文中,我们将看到如何使用JavaConfig配置和集成SpringMVC4,带有Hibernate的Spring Data JPA和SpringSecurity. 1. ...

  5. 使用JavaConfig的SpringMVC4 + Spring Data JPA + SpringSecurity配置

    在本文中,我们将看到如何使用JavaConfig配置和集成SpringMVC4,带有Hibernate的Spring Data JPA和SpringSecurity. 1.首先让我们在pom.xml中 ...

  6. Spring Data JPA - 参考文档-3

    参考文档 4. JPA存储库 本章将指出JPA对知识库的支持.这建立在使用Spring Data Repositories中解释的核心存储库支持上.所以要确保你对这里解释的基本概念有一个很好的理解. ...

  7. 具有中央异常处理和VO验证的Spring Data JPA –框架

    1.简介 一段时间以来,Spring框架已成为事实上的标准,可以创建任何基于REST API的应用程序. Spring提供了各种现成的组件,以避免编写重复而繁琐的样板代码. 另外,关于Spring的美 ...

  8. Spring Data JPA教程:获取所需的依赖关系

    在创建使用Spring Data JPA的应用程序之前,我们需要获取所需的依赖关系. 这篇博客文章标识了必需的组件,并描述了如何使用Maven获得它们. 让我们开始吧. 其他阅读:如果您不熟悉Spri ...

  9. Spring Data JPA 从入门到精通~自定义实现Repository

    EntityManager 的获取方式 我们既然要自定义,首先讲一下 EntityManager 的两种获取方式. 1. 通过 @PersistenceContext 注解. 通过将 @Persist ...

最新文章

  1. 运算符优先级记忆口诀及列表(转)
  2. SpringBoot多线程环境下,解决多个定时器冲突问题
  3. 什么是深度智能:2021年深度智能的发展趋势
  4. 5G商用元年!最新鲜热辣的使用指南看这里
  5. linux可以ping通,Linux可以Ping通但不能traceroute
  6. Python 列表推导式 - Python零基础入门教程
  7. 十二、程序返回、数据类型表示、代码注释
  8. devops_面向内向的人的DevOps
  9. c++运动学正反解 ros_朔州智能【机器人关节臂】哪家强
  10. 技术升级推动云游戏产业全面发展——白鹭科技陈书艺
  11. Web移动端常见问题-摘抄
  12. CentOS下安装两个或多个Tomcat7
  13. “程序员的理财计划”-待完善
  14. 【解决方案】校园明厨亮灶监控系统实施方案
  15. MFQ(海盗派探索性测试)学习记录
  16. word2007制作目录
  17. MYSQL间隙锁详解
  18. 手机html5活体检测,手把手教你做实时活体检测系统
  19. 平台设备驱动中的prob是怎么被调用的?为什么说是bus提供的probe优先调用?
  20. 小基础设施团队的分工思路

热门文章

  1. idea2021部署maven+javaweb项目到jboss(diy)
  2. 一文理类加载相关知识:类加载器、双亲委派、SPI
  3. RabbitMQ消息
  4. Springboot(十):邮件服务
  5. 备忘录模式 命令模式_备忘录设计模式示例
  6. 垃圾回收算法以及垃圾回收器_什么是垃圾回收?
  7. jboss4 迁移_JBoss BPM Travel Agency的微服务迁移故事
  8. unwind neo4j_Neo4j 2.1:传递节点ID与UNWIND
  9. 在Jetty中设置SSL
  10. java 常见错误_Java常见错误的十大列表(前100名!)