java - 当查找表连接它们时,Spring Boot 如何返回两个实体,其中一个嵌套在另一个实体中?
问题描述
给定一个包含 2 个表和它们之间的查找表的数据库的 Spring Boot Java 表示,两个表和查找表之间具有一对多的关系,如何以嵌套方式返回表示主表的两个实体?
目前,我只能弄清楚如何将它们并排返回,这对于前端发出请求时的要求来说不是一个合适的响应。
控制器为了方便而省略 - 它只返回服务 getAWithCNestedInIt()。
@Entity
class A{
@Id
@GenereatedValue(strategy = "GenerationType.IDENTITY")
@Column("a_id")
Integer A_Id;
Integer age;
// Relationship with lookup table:
@JsonIgnore
@ToString.Exclude
@OneToMany(mappedBy = "BLinkToA")
private Set <B> ASetLinkToB;
}
@Entity
// look-up table
class B{
@EmbeddedId
BKey id;
// Foreign keys to A and C
@ManyToOne
@MapsId("fk_A_Id")
@JoinColumn("fk_A_Id")
private A BLinkToA;
@ManyToOne
@MapsId("fk_C_Id")
@JoinColumn("fk_C_Id")
private C BLinkToC;
}
// B Key class here taken out to make code shorter.
@Entity
class C {
@Id
@GenereatedValue(strategy = "GenerationType.IDENTITY")
@Column("c_id")
Integer C_Id;
Integer foo;
// Relationship with lookup table:
@JsonIgnore
@ToString.Exclude
@OneToMany(mappedBy = "BLinkToC")
private Set <B> CSetLinkToB;
}
// A Controller calls and returns the following service method when URI "/getAandC" is hit
@Service
class TheServiceClass {
public List<List<Object>> getAWithCNestedInIt() {
List <A> aList = new ArrayList<A>();
List<List <C>> cList = new ArrayList<C>();
List<List<Object>> combinedList = new ArrayList <>();
// Assume this method does work to get the desired aList and cList here
///////// /////////
int i = 0;
for (A a: aList){
List<Object> instanceOfBoth = new ArrayList<>();
instanceOfBoth.add(a);
instanceOfBoth.add(cList.get(i));
combinedList.add(instanceOfBoth);
i++;
}
return combinedList;
}
}
编辑:JSON目前看起来像这样:
[[{
"age: "123"
},
[{
"foo": "456"
},
{
"foo": "789"
}]
],
[{
"age": "987"
},
[
{
"foo": "654"
},
{
"foo": "321"
},
{
"foo": "123"
}
]
]
]
我希望 JSON 响应是这样的:
[[
{
"age: "123",
CList:[{
"foo": "456"
},
{
"foo": "789"
}]
},
{
"age: "987",
CList:[{
"foo": "654"
},
{
"foo": "321"
},
{
"foo": "123"
}]
},
]
]
解决方案
您是否有理由不简单地创建一个表示您的响应应该如何看待并使用您的实体填充该表示的表示?
public class ATransferObject {
private Integer age;
private List<CTransferObject> CList;
// Methods omitted
}
public class CTransferObject {
private Integer foo;
// Methods omitted
}
这将您的实体与 JSON 表示分离,而是让您完全按照您想要的方式控制表示,而不是在实体中混合 JPA 和序列化。
推荐阅读
- node.js - node js 不希望你完成一个函数的执行
- node.js - 如何为 React/Node 应用程序上的 POST 请求修复 net::ERR_EMPTY_RESPONSE
- express - 传入的 Express 参数与传入的不一样
- java - 为什么此活动显示在新的 Android 版本中而不是旧版本中
- node.js - Mongoose 在空数组中找到结果,并且很确定所有模型都匹配
- c++ - 使用类时,计时器似乎运行得更快。在 C 版本中,它按预期工作
- math - 为什么在十进制到二进制转换期间反转余数?
- bash - 没有 Emacs,Bash 命令行编辑在 Emacs 模式下如何工作?
- azure - 移动应用:在 Xamarin.Forms 中使用“Microsoft.Azure.Cosmos”.NET SDK V3 - 跨平台
- c - 结构字段声明顺序在 Rust 中是否重要?