Issue
I have a rest api exposed via @RepositoryRestResource
from spring-data-rest-api
. When I try to give the json payload from Postman to create a User linked to an Organization, it complains that Column 'organizationId' cannot be null
, when I clearly provided it in the json.
{
"firstName": "Test",
"lastName": "User",
"email": "[email protected]",
"phoneNumber": "+12019582790",
"organizationId": "22bf93a5-e620-4aaf-8333-ad67391fb235",
"password": "example123",
"role": "admin",
}
Each user belongs to an organization, so it's a many to one relationship. I want Java to map the Organization that the User belongs to into the User as an Organization object.
User.java:
@Entity
@Table(name="user")
public class User {
@ManyToOne(targetEntity = Organization.class, fetch = FetchType.EAGER)
@JoinColumn(name = "organizationId", nullable = false)
private Organization organization;
}
Organization.java:
@Entity
@Table(name = "organization")
public class Organization {
@Id
@GeneratedValue(generator = "id-generator")
@Type(type = "uuid-char")
@Column(name="organizationId")
private UUID organizationId;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "organization")
private Set<User> users;
}
Any help is greatly appreciated.
Solution
This is the appoach I ended up going with. Still would like to know why the @ManyToOne
annotation isn't saving the organizationId as a foreign key in the User table by itself.
User.java:
@Type(type = "uuid-char")
@Column
private UUID organizationId;
@ManyToOne
@JoinColumn(name = "organizationId", insertable = false, updatable = false)
private Organization organization;
Answered By - Ethan Miller