我正在使用spring框架,Hibernate和JSON开发rest web app。 假设我有两个实体,如下所示:
University.java
public class University extends BaseEntity {
private String name;
private String address;
private String telephon;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER,orphanRemoval = true,mappedBy = "university")
@JsonManagedReference
private List<Student> students=new ArrayList<>();
// setter an getter
}
Student.java
public class Student extends BaseEntity{
private String firstName;
private String lastName;
private String section;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "UNIVERSITY_ID",nullable = false)
@JsonBackReference
private University university;
// setter an getter
}
我的要求:
当我打电话给学生列表api时,我需要在每个学生对象中都有Usiversity对象, 我需要什么样的配置或注释来处理这种情况? 结果是:
[
{
"id": 1,
"firstName": "aa",
"lastName": "aa",
"section": "aa"
},
{
"id": 2,
"firstName": "bb",
"lastName": "bb",
"section": "bb"
},
{
"id": 3,
"firstName": "cc",
"lastName": "cc",
"section": "cc"
}
]
我需要有这样的回复 当我打电话给学生名单
[
{
"id": 1,
"firstName": "aa",
"lastName": "aa",
"section": "aa",
"university": {
"id": 1,
"name": "string",
"address": "string",
"telephon": "string"
}
},
{
"id": 2,
"firstName": "bb",
"lastName": "bb",
"section": "bb",
"university": {
"id": 1,
"name": "string",
"address": "string",
"telephon": "string"
}
},
{
"id": 3,
"firstName": "cc",
"lastName": "cc",
"section": "cc",
"university": {
"id": 3,
"name": "www",
"address": "www",
"telephon": "www"
}
}
]
更新
对于大学名单我需要这个回复
[
{
"id": 1,
"name": "string",
"address": "string",
"telephon": "string",
"students": [
{
"id": 1,
"firstName": "aa",
"lastName": "aa",
"section": "aa"
},
{
"id": 2,
"firstName": "bb",
"lastName": "bb",
"section": "bb"
}
]
},
{
"id": 3,
"name": "www",
"address": "www",
"telephon": "www",
"students": [
{
"id": 3,
"firstName": "cc",
"lastName": "cc",
"section": "cc"
}
]
}
]
任何帮助和建议表示赞赏。
答案 0 :(得分:1)
我认为杰克逊的注释被宣布为错误的方式:
@JsonManagedReference是引用的前向部分 - 正常序列化的部分。
@JsonBackReference是引用的后半部分 - 它将从序列化中省略。