My Employees need to have a role, which later could be extended with other attributes. Because of that, I want to keep them as separate entities.
In the Employee class, I am referencing a role like this:
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)
private EmployeeRole role;
while the EmployeeRole class has only a numeric id attribute and a description as a String.
Goal
Whenever I create an entity of type Employee, I want to specify only the description of a role, not its id. If the role with such description already exists, its id is what is used as the role_id foreign key on the Employee relation.
Otherwise, a new role is created.
Current behavior
New EmployeeRole is created for each Employee. If I set the description to be unique:
@Column(unique = true)
private String description;
an Employee is not created if a role with the specified description already exists.
Solution?
A possible solution is to check whether an EmployeeRole with this description already exists, create it if it doesn't, and in both cases utilize its id to map a new Employee to it.
I honestly do not know how to do that in class declaration. Any suggestions are appreciated.