Reputation: 536
I am trying to achieve Many to one relationship where stations are belong to regions. How can I achieve this using REST to create station by just passing the region ID in the POST station json as shown.
{
"name": "New York",
"code": "MGR",
"active": "YES",
"regionid": 1
}
Below is my controller.
@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;
}
Below are my models.
@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;
}
Upvotes: 1
Views: 738
Reputation: 536
I realized I do not need @JsonManagedReference Thus my code will be
@ManyToOne
@JsonProperty("regionID")
@JoinColumn(name = "regionid", referencedColumnName = "regionID")
private Region region;
And boommmm.......
Upvotes: 0
Reputation: 9457
@JoinColumn(name = "regionid", referencedColumnName = "regionid")
private Region region;
referencedColumnName
not exist in Regioin class. It will be regionID
instead of regionid
.
Try with below change:
@JoinColumn(name = "regionid", referencedColumnName = "regionID")
private Region region;
Upvotes: 1