1

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.

kirusfg
  • 27
  • 1
  • 4
  • if you use a `@OneToOne` each `Employee` needs to have a different `EmployeeRole` (read id) reference: [manytoone-vs-onetoone](https://stackoverflow.com/questions/18460469/hibernate-manytoone-vs-onetoone) – Dirk Deyne Dec 06 '21 at 21:25

1 Answers1

1

Perhaps this is not what you are looking for, but you could query EmployeeRole by the description and reuse the entity for your employee if it exist or create a new one if not. If you use JpaRepository you could write a method in it like this in the interface to create the query by desecription column:

EmployeeRole findFirstByDescription(String description);

Technically you could just name the method:

EmployeeRole findByDescription(String description); 

But then it will not work if you for some reason would accidentally create multiple EmployeeRoles with the same description so by using "findFirst.." you eliminate that just in case.

Vanheden
  • 582
  • 5
  • 14