我有一个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类hashcode()和equals()方法,因为Set对象不会获取重复数据

09-25 16:34