使用json创建@ManyToOne对象

时间:2019-02-23 23:22:00

标签: hibernate spring-mvc jackson spring-data-jpa

我正在尝试实现站点属于区域的多对一关系。如何通过使用REST通过仅在POST站点json中传递区域ID来使用REST创建站点,来实现这一点。

{
    "name": "New York",
    "code": "MGR",
    "active": "YES",
    "regionid": 1

}

下面是我的控制器。

@PostMapping("/station/create/")
public ResponseObject create(@Valid @RequestBody Station station){
    ResponseObject responseObject = new ResponseObject();
    responseObject.setSuccess(true);
    responseObject.setData(stationDao.save(station));
    responseObject.setMessage("Station created successfully");
    return responseObject;
}

下面是我的模特。

@Entity
@Table(name = "regions")
@EntityListeners(AuditingEntityListener.class)
public class Region implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty("regionID")
    private Long regionID;
    @JsonProperty("name")
    private String name;
    @JsonProperty("active")
    @Enumerated(EnumType.STRING)
    private YesNo active;
}





@Entity
@Table(name = "stations")
@EntityListeners(AuditingEntityListener.class)
public class Station implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty("stationID")
    private Long stationID;

    @JsonManagedReference
    @ManyToOne
    @JsonProperty("regionID")
    @JoinColumn(name = "regionid", referencedColumnName = "regionid")
    private Region region;

    @JsonProperty("name")
    private String name;
    @JsonProperty("code")
    private String code;
    @JsonProperty("active")
    @Enumerated(EnumType.STRING)
    private YesNo active;
}

2 个答案:

答案 0 :(得分:1)

@JoinColumn(name = "regionid", referencedColumnName = "regionid")
    private Region region;

referencedColumnName在Regioin类中不存在。它将是regionID而不是regionid

尝试以下更改:

@JoinColumn(name = "regionid", referencedColumnName = "regionID")
        private Region region;

答案 1 :(得分:0)

我意识到我不需要@JsonManagedReference 因此,我的代码将是

    @ManyToOne
    @JsonProperty("regionID")
    @JoinColumn(name = "regionid", referencedColumnName = "regionID")
    private Region region;

还有宝贝....