我有一个带有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);
}
客户端.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 个波斯托和 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 倍相同的卢斯对象。它也发生了我的情况颠倒了,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
因为对象不获取 dublicate 数据