定制Spring Data JPA存储库

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添加Hibernate过滤器功能。

参考:来自我们的JCG合作伙伴 Boris Lam在Programming Peacely博客上定制Spring Data JPA存储库 。


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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/353838.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ubuntu+eclipse+svn

ubuntueclipsesvn 2010-06-23 16:02:32| 分类&#xff1a; 默认分类 |字号 订阅 昨天装了一天的CVS,但是始终无法启动CVSD&#xff0c;防火墙也没有开&#xff0c;不知道是什么原因&#xff0c;无奈之下只好转向了SVN&#xff0c;也当是学习一下&#xff5e;&#xff5e;&…

Log4j 2.x XSD的描述不完整

在博客文章JAXB和Log4j XML配置文件中 &#xff0c;我讨论了“与使用JAXB通过Java类处理[Log4j 1.x和Log4j 2.x] XML配置文件相关的细微差别。” 在本文中&#xff0c;我将探讨另一个与通过Log4j 2.x XML Schema文件Log4j-config.xsd生成的JAXB对象生成Log4j 2.x配置XML相关的挑…

Protobuf学习笔记

Protobuf学习笔记 Posted by iamxhuon 2012/05/22 Leave a comment (0)Go to commentsProtocol buffers是什么&#xff1f; 首先了解一下Protocol Buffers(简称ProtoBuf)是什么&#xff1f;官网对它的定义如下&#xff1a; Protocol buffers are Google’s language-neutral, …

如何掌握Java内存(并保存程序)

通过AppDynamics解决应用程序问题的速度提高了10倍–以最小的开销在代码级深度监视生产应用程序。 开始免费试用&#xff01; 您花了无数小时来研究Java应用程序中的错误并在需要的地方获得其性能。 在测试期间&#xff0c;您注意到应用程序随着时间的推移逐渐变慢&#xff0c…

程序集版本号

程序集版本号分为4段&#xff0c;例如1.0.4.23。 第一段为主版本号&#xff0c;项目一但启动则不会更改。 第二段为次版本号&#xff0c;在项目功能做较大调整时增加&#xff0c;增量为1。 第三段为修订版本号&#xff0c;通常在解决缺陷或者细微功能变化时增加&#xff0c;增量…

py-kms使用方法

搭建py-kms服务器,先下载py-kms https://github.com/myanaloglife/py-kms 启动py-kms服务(需要服务器安装有python): python server.py 这样py-kms服务就启动好了,如果需要后台运行可以制作deamon脚本。 py-kms可以激活企业/专业版vl windows系统和vol版本的office软件: window…

JAVA泛型--待续

原做法&#xff1a; Map m new HashMap();m.put("key", "blarg");String s (String) m.get("key"); 泛型做法&#xff1a; Map<K,V> m new HashMap()<K,V>;m.put("key", "blarg");//非<K,V>类型无法操…

Tortoise SVN 版本控制常用操作知识

Tortoise SVN 版本控制常用操作知识 Posted on 2010-11-26 23:07 szh114 阅读(5897) 评论(0) 编辑 收藏 今天老大跑过来问我如何把SVN服务器上的当前版本回退到某一个版本上去&#xff0c;我没回答上来&#xff0c;很失败&#xff0c;所以现在整理一下Tortoise SVN的操作知识&…

如何导入任何JBoss BRMS示例项目

在过去几周内&#xff0c;JBoss BRMS演示的用户反复询问我以下内容时&#xff0c;会给您这些提示和技巧&#xff1a; “如何将与各种JBoss BRMS演示项目相关的项目导入到我自己的现有安装中&#xff1f;” 这意味着用户希望在产品的个人安装中有一个示例项目&#xff0c;而无…

2110: 扫雷

http://acm.zcmu.edu.cn/JudgeOnline/problem.php?id2110 2110: 扫雷 Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 88 Solved: 36[Submit][Status][Web Board]Description 扫雷游戏你一定玩过吧&#xff01;现在给你若干个nm的地雷阵&#xff0c;请你计算出每个矩阵中每…

使用eclipse生成文档(javadoc)

使用eclipse生成文档&#xff08;javadoc&#xff09;主要有三种方法&#xff1a; 1&#xff0c;在项目列表中按右键&#xff0c;选择Export&#xff08;导出&#xff09;&#xff0c;然后在Export(导出)对话框中选择java下的javadoc&#xff0c;提交到下一步。 在Javadoc Gene…

青椒苗

转载于:https://www.cnblogs.com/wainiwann/p/8793418.html

更改日志级别_如何在运行时更改日志记录级别

更改日志级别在运行时中更改日志记录级别非常重要&#xff0c;这主要在生产环境中非常重要&#xff0c;在生产环境中&#xff0c;您可能希望在有限的时间内进行调试日志记录。 好了&#xff0c;更改根记录器非常简单–假设您有一个具有所需记录级别的输入参数&#xff0c;只需…

JDBC和Ibatis中的Date,Time,Timestamp处理

JDBC和Ibatis中的Date,Time,Timestamp处理 November 25th, 2010西坪 Leave a commentGo to comments在此前&#xff0c;遇到过使用Ibatis操作Oracle时时间精度丢失的问题&#xff0c;昨天又遇到JDBC操作MySQL时间字段的问题&#xff0c;从网上看到各种式样的解释这些问题的博文…

每日算法之抽签

X星球要派出一个5人组成的观察团前往W星。其中&#xff1a;A国最多可以派出4人。B国最多可以派出2人。C国最多可以派出2人。....那么最终派往W星的观察团会有多少种国别的不同组合呢&#xff1f;下面的程序解决了这个问题。数组a[] 中既是每个国家可以派出的最多的名额。程序执…

如何开始Java机器学习

什么是开始使用Java机器学习的最佳工具&#xff1f; 他们已经存在了一段时间&#xff0c;但如今看来&#xff0c;每个人都在谈论人工智能和机器学习。 对于科学家和研究人员而言&#xff0c;它已不再是秘密&#xff0c;几乎可以在任何新兴技术中实现。 在下面的文章中&#x…

keil中关于使用_at_绝对地址定位问题

keil中关于使用_at_绝对地址定位问题 2008-01-07 13:46:26| 分类&#xff1a; MCU51 | 标签&#xff1a; |字号大中小 订阅 在网上看到有人提到在keil中使用_at_进行绝对地址定位问题&#xff0c;我简单介绍一下它的用法。 使用_at_关键字对存储器进行绝对地址定位程序…

ztree树

常规的ztree树 后台数据封装成list对象 public PageModel getTreeBuildingRegData(Map<String, String> params) {PageModel pageModelnew PageModel();String statusparams.get("status");String orgIdparams.get("org_id");List<OmsBuildingReg…

如何提高效率

如何提高效率 时间管理 April 28th, 2011 本文来自读者 桃雨 翻译投稿。 Aaron Swartz写过一篇很有名的文章&#xff0c;叫做《HOWTO: Be more productive》&#xff08;如何提高效率&#xff09;。这篇文章写的实在是太好了&#xff0c;我看了好多遍&#xff0c;很赞同作者的…

Andrew Ng - 深度学习工程师 - Part 2. 改善深层神经网络:超参数调试、正则化以及优化(Week 1. 机器学习的实用层面)...

第1周 机器学习的实用层面 1.1 训练/开发/测试 早期机器学习时代&#xff08;数据规模较小&#xff09;&#xff0c;如果不需要dev set&#xff0c;常见的划分有 70%/30% 的训练/测试 划分&#xff0c;如果需要验证集&#xff0c;常见的是 60%/20%/20%划分 在big data era&…