Spring JPA中的通用存储库 [英] Generic Repository in Spring JPA

查看:131
本文介绍了Spring JPA中的通用存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在一个带有大量数据库表的Restful项目.尽管表上的操作几乎相同,并且主要是INSERT/UPDATE/DELETE/FETCH.

We are working on a Restful project with lots of DB tables. Though the operations on the tables are almost same and mainly INSERT/UPDATE/DELETE/FETCH.

我的问题是:
我们是否必须为我们创建的每个实体(Domain类)创建一个存储库(扩展JpaRepository),还是可以选择创建一个GenericRepository来处理所有上述实体的所有功能? 即所有的单一GenericRepository.

my questions is:
will we have to create a repository (extending JpaRepository) for every entity (Domain class) we create or, there is an option of creating a GenericRepository that can handle all the above-mentioned functionalities for all the entities? i.e a single GenericRepository for all.

如果是这样,您能分享一个例子吗?

if so, could you share an example?

推荐答案

[存在]创建一个可以处理所有实体的所有上述功能的GenericRepository的选项吗?

您正以错误的假设来考虑此问题:实际上,您实际上不应该针对每个表/实体拥有一个存储库,而应针对每个Aggregate(Root)拥有一个存储库.请参阅>您是否应该在每个表中有一个存储库在JPA中?以获得更多详细信息.

You are looking at this with a wrong assumption: You are really not supposed to have a repository per table/entity but per Aggregate(Root). See Are you supposed to have one repository per table in JPA? for more details.

第二:拥有通用存储库违反了Spring Data JPA的目的,毕竟,JPA已经拥有通用存储库.它称为EntityManager.因此,如果您只需要提到的操作,则只需注入EntityManager就可以了.完全不需要使用Spring Data JPA.而且,如果您希望在业务代码和JPA规范之间包含一些内容,可以将其包装在一个简单的存储库中,如 @AlexSalauyou .

Second: Having a generic repository kind of defies the purpose of Spring Data JPA, after all, JPA already has a generic repository. It's called EntityManager. So if you just need the operations you mentioned, just injecting an EntityManager should be fine. No need to use Spring Data JPA at all. And if you want to have something between your business code and JPA specifics, you can wrap it in a simple repository as described by @AlexSalauyou.

最后一点:您将拥有在某个地方创建所有表的代码.您还将拥有所有实体的代码.并且您有用于测试此代码.每个接口都有琐碎的接口定义会成为问题吗?

One final point: You'll have the code to create all the tables somewhere. You'll also have the code for all the entities. And you have the code for testing this. Is having a trivial interface definition for each going to be a problem?

这篇关于Spring JPA中的通用存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆