如何在JAVA JPA Spring Boot中的一个SQL查询中选择多个数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在JAVA JPA Spring Boot中的一个SQL查询中选择多个数据相关的知识,希望对你有一定的参考价值。
我有用户实体,其中包含组列表。每个组都有两个列表:submissionDocumentType和reviewDocumentType。使用尽可能少的数据库调用获取User的GroupDetails对象列表的最有效方法是什么(请参阅下面的最终预期结果)?
user.Java
public class User {
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@ManyToMany(mappedBy = "users")
private Set<UserGroup> userGroups;
用户组
public class UserGroup {
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@ManyToMany(mappedBy = "submissionUserGroups")
private List <DocumentType> submissionDocumentType;
@ManyToMany(mappedBy = "reviewUserGroups")
private List <DocumentType> reviewDocumentType;
group details.Java
public class GroupDetails {
private String groupTitle;
private List<String> reviewDocTypes;
private List<String> submitDocTypes;
GET方法的预期响应
[
{
"groupTitle": "Group one",
"reviewDocTypes": [
"Prasymas Eazy",
"Prasymas Tgwz",
"Prasymas Gien",
"Prasymas Docs",
"Prasymas Ecyd",
"Prasymas Sjvz"
],
"submitDocTypes": [
"Prasymas Buor",
"Prasymas Kzhc",
"Prasymas Zokx",
"Prasymas Vvtb",
"Prasymas Docs",
"Prasymas Lutj",
"atostogu prasymas"
]
},
{
"groupTitle": "Group two",
"reviewDocTypes": [
"Prasymas Tgwz",
"Prasymas Gien",
"Prasymas Kzhc",
"Prasymas Kblj",
"Prasymas Docs",
"Prasymas Ecyd"
],
"submitDocTypes": [
"Prasymas Tgwz",
"Prasymas Wmwx",
"Prasymas Buor",
"Prasymas Gien",
"Prasymas Kzhc",
"Prasymas Kblj",
"Prasymas Docs",
"Prasymas Xdau",
"Prasymas Lutj",
"Prasymas Ecyd",
"atostogu prasymas"
]
}
]
答案
我想你可以在一个查询中做到这一点。正如你在the reference documentation中看到的:
Spring Data允许建模专用返回类型,以更有选择地检索托管聚合的部分视图。将查询结果限制为仅名称属性的最简单方法是声明一个接口,该接口公开要读取的属性的访问器方法
所以我们可以使用这样的查询方法获取结果:
interface UserRepository extends Repository<User, String> {
Collection<GroupDetails> findById(String userId);
}
以上是关于如何在JAVA JPA Spring Boot中的一个SQL查询中选择多个数据的主要内容,如果未能解决你的问题,请参考以下文章
Spring Data JPA在Spring Boot中的应用
Spring boot之 JPA/Hibernate/Spring Data