What is the best/common solution (best practices) to working with relationships in ORM (from long-life project view)?
1) E.g. I have Oracle HR schema. Is it ok to create relations between every objects (entities) where it is possible or only between objects where I really need now (and change in future)?
@Entity
public class Employee {
@Id
private long employeeId;
@ManyToOne((fetch = FetchType.LAZY)
private Job job;
}
@Entity
public class Job {
@Id
private String jobId;
@OneToMany(fetch = FetchType.LAZY)
private List<Employee> employeeList;
}
2) How should I store/set new Employee with existing or new Job? We have Employee entity with String jobId and also created relation Job job variable:
@Entity
public class Employee {
@Id
private long employeeId;
private String jobId;
@ManyToOne((fetch = FetchType.LAZY)
private Job job;
}
The worst solutions is set both parameters everytime:
Job job = new Job();
job.setJobId("JOB_01");
Employee employee = new Employee();
employee.setEmployeeId(1L)
employee.setJobId(job.getJobId());
A little bit better solutions is re-implement setJobId() method in Employee class (there should be also some code to find out if mentioned Job exist or not):
public void setJobId(String jobId) {
if (getJob() == null) {
this.jobId = jobId;
job = new Job();
job.setJobId(jobId);
} else {
this.jobId = getJob().getJobId();
}
}
If you don’t need an association, then you don’t need to add it. Note however that even if it’s not used in Java code directly, an association might still be useful just to be able to traverse it in JPQL or criteria queries.
Regarding your jobId field, it should just be removed from the
Employeeentity. An employee has a job, and you can access its job ID usingemployee.getJob().getId(). You shouldn’t be able to set the job ID of an employee. Instead, you should get or create a job (in the service layer), and set the employee’s job usingsetJob(job).