繁体   English   中英

Spring Boot-奇怪的JSON控制器响应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM