user3521432 user3521432 - 1 month ago 16
Java Question

Using relationships like @OneToMany, @ManyToOne in hibernate is good practice or not?

Using relationships like @OneToMany, @ManyToOne in java spring Boot hibernate project is good practice or not?

Answer

Regardless of good practice, the point here is you have two options to model this:

  1. Elect to manually assign the Department's Id on the Employee.
  2. Associate the new Employee with an existing Department entity at save.

Which you pick really depends on a number of factors.

Often the former is chosen when working with legacy systems where foreign key constraints were not imposed or in situations where you don't want to impose those constraints. This is often more of the rarer case of the two, but it makes sense under specific circumstances.

The latter is the more favored approach because the entity domain model best represents not only the restrictions and constraints implied by the database model, but also conveys the restrictions that your domain expert uses. For example, an Employee cannot be saved without being associated to a valid Department. Therefore, you assign a Department to the employee and not its identifier.

Naturally the choice you take will have some influence on the types of queries you can issue against the entity model, but the impact is minimal.

private Department getDepartmentById(Long departmentId)
  throws InvalidDepartmentException {
  try {
    return entityManager.getReference( Department.class, departmentId );
  }
  catch ( EntityNotFoundException e ) {
    throw new InvalidDepartmentException( departmentId, e );
  }
} 

private List<Employee> getEmployeesNoAssociation(Long departmentId) 
  throws InvalidDepartmentException {
  final Department dept = getDepartmentById( departmentId );
  return entityManager
    .createQuery( "SELECT e FROM Employee e WHERE e.departmentId = :id", Employee.class )
    .setParameter( "id", dept.getId() )
    .getResultList();
}

private List<Employee> getEmployeesWithAssociation(Long departmentId) 
  throws InvalidDepartmentException {
  final Department dept = getDepartmentById( departmentId );
  return entityManager
    .createQuery( "SELECT e FROM Employee e WHERE e.department = :dept", Employee.class )
    .setParameter( "dept", dept )
    .getResultList();
}

In short, good practice is to model your domain as its intended to be used. How that applies to whether you use association mappings depends highly on context of your situation.