0

On a bidirectional relationship in hibernate/JPA, which entity (or both?) do you specify the fetch mode and cascade type? An example:

@Entity
@Table(name="EMPLOYER")
public Employer implements Serializable
{
     @OneToMany(mappedBy="employer")
     private Set<Employee> employees;
}

@Entity
@Table(name="EMPLOYEE")
public Employee implements Serializable
{
     @ManyToOne
     @JoinColumn(name="employer_id", referencedColumnName="id")
     private Employer employer;
}

Do I put the fetch mode and cascade type on the owner of the relation (Employee)? Or do I put them on the inverse (Employer)? Or do (can?) I put them on both? I'm quite confused on the cascading in JPA/Hibernate. I am guessing that I can put the fetch mode on both and this will determine how Employer will fetch the Set of Employees and how Employee will fetch his Employer. I am making this assumption because @OneToMany and @ManyToOne have default fetch modes already.

I am unclear on how the cascade type works. Does that go on both and that determines what gets cascaded for an Employer and what gets cascaded for an Employee? Any help is much appreciated.

The parent/child relation and how cascade modifies them is the most confusing part for me.

Leveticus
  • 33
  • 1
  • 7

1 Answers1

0

You can define a fetch mode on both sides of the relationship. The fetch mode does not depend on the relationship mapping. Since eager fetching is the default, you should define only lazy fetching explicitly. Please note that lazy fetching is just a hint, so the provider is free to fetch the attributes eagerly as it sees fit.

You should not define cascades from a many side. The semantics of cascading from the many side are undefined by the JPA spec. The provider is thus free to implement it's own semantics or even throw an exception. So in your case, only the employees attribute of the Employer entity may define cascading.

kostja
  • 60,521
  • 48
  • 179
  • 224