0
我正在開發與Spring框架,休眠和JSON的其餘Web應用程序。 假設我有一個像下面兩個實體:Spring Rest和Hibernate和JSON dosnt按預期工作
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,我需要在每個學生對象中使用大學對象, 我需要用什麼樣的配置或註釋來處理這種情況? 結果是:
[
{
"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"
}
]
}
]
任何幫助和建議表示讚賞。
我需要在大學方面有@JsonManagedReference。因爲如果我刪除它,我無法熱切地獲得大學名單。 – Generic
爲什麼?一個是JPA,另一個是JSON序列化。 –
jpa完美地完成它,但是當我急切地需要雙方時,它會在json中遇到麻煩。它擁有@JsonManagedReference哪一方面會起作用。 – Generic