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

查看:23
本文介绍了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.

我的问题是:
我们是否必须为我们创建的每个实体(域类)创建一个存储库(扩展 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 可以处理所有实体的所有上述功能的选项?

is [there] an option of creating a GenericRepository that can handle all the above-mentioned functionalities for all the entities?

您正在以错误的假设看待此问题:您真的不应该为每个表/实体而是每个聚合(根)拥有一个存储库.请参阅您是否应该每张表有一个存储库在 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天全站免登陆