'Unable to store ManyToOne association for an entity
I am unable to bind foreign_key baz_id to Baz on a POST call, it fails with a instantiation error trying to store a bar
POST http://localhost/foo/api/v1/bars
{
"baz_id" : "1",
"weight" : "1.0"
}
@NotNull
@ManyToOne
@JoinColumn(name = "baz_id", nullable = false, referencedColumnName = "id")
private Baz baz;
Solution 1:[1]
Your JSON is incorrect for the object being mapped. It should be of the form:
{
"baz" : {"id":"1"},
"weight" : "1.0"
}
this will allow Spring to build a bar instance that references a Baz instance with an id of 1.
Alternatively, if you use
{
"baz_id" : "1",
"weight" : "1.0"
}
your java entity will need to define a 'baz_id' property within it:
@Transient
private String baz_id;
Which your controller then uses to decide how to handle this value; ie using the appropriate findbyId method to set the baz reference before saving your Bar instance - this also gives you the opportunity to validate it does exist and decide what to do if it doesn't; create a new one or throw an appropriate exception.
Alternatively, you can map the String basic to the column, and only use that to set the value:
@ManyToOne
@JoinColumn(name = "baz_id", referencedColumnName = "id", insertable=false, updatable=false, fetch = FetchType.LAZY )
@JsonIgnore
private Baz baz;
@Column(name = "baz_id", nullable = false)
private String baz_id;
This will let you use the baz_id for REST api, but the baz reference for joins and other application usage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris |