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

时间:2016-03-18 17:59:36

标签: java json spring

我有一个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 Luce和1 Posto,我得到两倍的唯一Posto。 如果所有Posto和Luce对象都链接到idClient 1,那么响应是好的,如果我没有用于IdClient的Luce(或没有Posto),那也很好... 我不知道在哪里看,一切似乎都有效,我没有错误......

1 个答案:

答案 0 :(得分:1)

更改列表以在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数据