Spring:获取ManyToOne实体时,引用实体(OneToMany)未显示在JSON中

时间:2016-09-22 15:06:01

标签: java json spring spring-mvc spring-data-jpa

当我在POSTMAN中发送GET请求以获取我的所有子实体(Town)时,父实体(省)未显示在JSON响应中。

这是我的控制器。

@RequestMapping(value ="api/v1/town",method = RequestMethod.GET)
public ResponseEntity<List<Town>> getAllTowns() {
    List<Town> towns = townService.getAllTowns();
    if(towns.isEmpty()) {
        return new ResponseEntity<List<Town>>(HttpStatus.NO_CONTENT);
    }

    return new ResponseEntity<List<Town>>(towns, HttpStatus.OK);
}

这些是我的实体。

父类

@Entity
@Table(name = "PROVINCE")
public class Province {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "PROVINCE_ID")
    private long id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "province", targetEntity = Town.class)
    @JsonManagedReference("Province-Town")
    private List<Town> towns;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Town> getTowns() {
        return towns;
    }

    public void setTowns(List<Town> towns) {
        this.towns = towns;
    }
}

儿童班

@Entity
@Table(name = "TOWN")
public class Town {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "TOWN_ID")
    private long id;

    private String name;

    @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "PROVINCE_ID")
    @JsonBackReference("Province-Town")
    private Province province;

    private long kilometer;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Province getProvince() {
        return province;
    }

    public void setProvince(Province province) {
        this.province = province;
    }

    public long getKilometer() {
        return kilometer;
    }

    public void setKilometer(long kilometer) {
        this.kilometer = kilometer;
    }
}

我得到的回应是这样的

{
    "id" : 1,  
    "name" : "Some Town",
    "kilometer" : 350
}

我期待的是

{
    "id" : 1,  
    "name" : "Some Town",
    "province" : { 
             //Province data.....
     }
    "kilometer" : 350
}

我能够显示这样的东西,但我使用的对象不是Spring-data-jpa实体,只是简单的POJO。

我的实体有什么问题吗?或者还有别的吗?

1 个答案:

答案 0 :(得分:1)

交换@JsonBackReference@JsonManagedReference。基本上是:

@JsonManagedReference
private Province province;

@JsonBackReference
private List<Town> towns;