[英]Spring boot - Strange JSON Controller response
我有一個SpringBoot應用程序。 我有一個簡單的RestController:
@RestController
public class ClientController {
private static final Logger logger = Logger.getLogger(ClientController.class);
@Autowired ClientService clientService;
@RequestMapping(value = "/client", method = RequestMethod.GET)
public ResponseEntity<Client> getClient(@RequestParam(value = "idClient") int idClient)
{
Client client = clientService.findById(idClient);
return new ResponseEntity<Client>(client, HttpStatus.OK);
}
Client.java有2個OneToMany字段Luce和Posto,用以下方式注釋:
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client")
public List<Posto> getPosti() {
return posti;
}
public void setPosti(List<Posto> posti) {
this.posti = posti;
}
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client")
public List<Luce> getLuci() {
return luci;
}
public void setLuci(List<Luce> luci) {
this.luci = luci;
}
當我嘗試調用url時,響應出現奇怪的行為。 假設我有2個Posto和2個Luci對象。 Posto對象鏈接到idClient = 1,只有一個Luce鏈接到idClient = 1。 因此,例如,如果我點擊了http://localhost:8080/client?idClient=1
我應該得到2個Posto和1個Luce,但是我得到以下響應(為簡便起見,我刪除了一些不重要的字段):
{
"idClient": 1,
"posti": [
{
"idPosto": 1,
"numeroPosto": 61,
"nomePosto": "Posto numero 61"
},
{
"idPosto": 2,
"numeroPosto": 152,
"nomePosto": "Posto numero 62"
}
],
"luci": [
{
"idLuce": 1,
"numeroLuce": 1,
"nomeLuce": "Lampada 1",
},
{
"idLuce": 1,
"numeroLuce": 1,
"nomeLuce": "Lampada 1",
}
]
}
所以我得到了2個相同的Luce對象。 如果情況倒轉,也發生了這種情況:2個Luce和1個Posto,我得到的是唯一Posto的兩倍。 如果所有Posto和Luce對象都鏈接到idClient 1,則響應很好,如果我沒有IdClient的Luce(或Posto),響應也很好...我不知道從哪里看,一切似乎工作,我沒有任何錯誤...
更改列表以在Client.java
類中設置
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client")
public Set<Posto> getPosti() {
return posti;
}
public void setPosti(Set<Posto> posti) {
this.posti = posti;
}
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client")
public Set<Luce> getLuci() {
return luci;
}
public void setLuci(Set<Luce> luci) {
this.luci = luci;
}
並實現Client.java
類的hascode()和equals()方法,因為Set
對象不會獲取重復數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.