gpt4 book ai didi

java - Spring boot - 奇怪的 JSON Controller 响应

转载 作者:行者123 更新时间:2023-12-01 10:11:40 27 4
gpt4 key购买 nike

我有一个带有 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;
}

当我尝试调用该网址时,我得到了奇怪的响应行为。假设我有 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",

}
]
}

所以我得到了同一个 Luce 对象的 2 倍。当情况颠倒时也会发生这种情况,2个卢斯和1个波斯托,我得到了唯一波斯托的两倍。如果所有 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对象不接受重复数据

关于java - Spring boot - 奇怪的 JSON Controller 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com