定制Spring Data JPA存储库
组态
您必须在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添加Hibernate过滤器功能。
参考:来自我们的JCG合作伙伴 Boris Lam在Programming Peacely博客上定制Spring Data JPA存储库 。
翻译自: https://www.javacodegeeks.com/2012/08/customizing-spring-data-jpa-repository.html
定制Spring Data JPA存储库相关推荐
- 自定义Spring Data JPA存储库
Spring Data是一个非常方便的库. 但是,由于该项目是一个相当新的项目,因此功能不佳. 默认情况下,Spring Data JPA将基于SimpleJpaRepository提供DAO的实现. ...
- 使用Spring Data REST将Spring Data JPA存储库导出为REST服务
Spring Data模块提供了各种模块,以统一的方式处理各种类型的数据源,如RDBMS,NOSQL存储等. 在我以前的文章SpringMVC4 + Spring Data JPA +使用JavaCo ...
- Spring Data Redis存储库
8. Redis存储库 使用Redis存储库允许在Redis哈希中无缝地转换和存储域对象,应用自定义映射策略并利用二级索引. Redis存储库至少需要Redis Server 2.8.0版. 8.1. ...
- Spring Data JPA - 参考文档-3
参考文档 4. JPA存储库 本章将指出JPA对知识库的支持.这建立在使用Spring Data Repositories中解释的核心存储库支持上.所以要确保你对这里解释的基本概念有一个很好的理解. ...
- springmvc jpa_使用JavaConfig的SpringMVC4 + Spring Data JPA + SpringSecurity配置
springmvc jpa 在本文中,我们将看到如何使用JavaConfig配置和集成SpringMVC4,带有Hibernate的Spring Data JPA和SpringSecurity. 1. ...
- 使用JavaConfig的SpringMVC4 + Spring Data JPA + SpringSecurity配置
在本文中,我们将看到如何使用JavaConfig配置和集成SpringMVC4,带有Hibernate的Spring Data JPA和SpringSecurity. 1.首先让我们在pom.xml中 ...
- 具有中央异常处理和VO验证的Spring Data JPA –框架
1.简介 一段时间以来,Spring框架已成为事实上的标准,可以创建任何基于REST API的应用程序. Spring提供了各种现成的组件,以避免编写重复而繁琐的样板代码. 另外,关于Spring的美 ...
- Spring Data JPA教程:获取所需的依赖关系
在创建使用Spring Data JPA的应用程序之前,我们需要获取所需的依赖关系. 这篇博客文章标识了必需的组件,并描述了如何使用Maven获得它们. 让我们开始吧. 其他阅读:如果您不熟悉Spri ...
- Spring Data JPA(官方文档翻译)
关于本书 介绍 关于这本指南 第一章 前言 第二章 新增及注意点 第三章 项目依赖 第四章 使用Spring Data Repositories 4.1 核心概念 4.2 查询方法 4.3 定义rep ...
最新文章
- Windows Azure Platform Introduction (6) Windows Azure应用程序运行环境
- c++实现多态的方法 虚表
- java正则表达式去除xml标签之间的空格_HTML解析器——htmlparser2使用详解,换个姿势解析html和xml
- JavaScript笔记(3)
- Pycharm如何导入python包
- man hdparm
- jetCache使用
- matlab求方程实根,简单迭代法求方程根的MATLAB程序
- c# 如何获取项目的根目录
- 【JavaScript学习笔记】计算机编程基础
- bxp帮助文档(转)
- IBM SPSS Modeler 【3】 神经网络的生成
- 知识图谱从入门到应用——知识图谱的知识表示:向量表示方法
- CSS层叠样式表(Cascading Style Sheets)
- k8s添加pod,k8常用命令,k8s删除pod
- 非对称加密 DSA算法
- maven java archetype_Maven-自定义工程骨架archetype
- 【从0到1完成一个项目(一)】用户中心(上)
- 调整VM虚拟机显示窗口大小
- JPEG图像压缩算法流程详解
热门文章
- eclipse xml文件中按没有提示
- Spring Boot中mapper包所放位置的配置
- jQuery操作DOM元素案例
- 最全三大框架整合(使用映射)——struts.xml和web.xml配置
- Spring的properties属性配置文件和Spring常用注解
- 2020蓝桥杯省赛---java---C---3( 跑步训练)
- 基于ZooKeeper实现HA高可用性以及自动主备切换
- (转)如何查看java本地方法
- 字节数组转jsonobject(如读取HttpServletRequest.inputstream到jsonobject)
- kafka消费者开发方式小结