0

I have read some code describing relationship of two entities on both sides which look like following:

public class Department {
    @OneToMany(mappedBy = "department",fetch = FetchType.EAGER , cascade = CascadeType.ALL)
    private List<Course> courses = new ArrayList<>();
}

public class Course {
 @ManyToOne
    private Department department;
}

There are two scenarios: When I use relationship annotation on both sides("on both tables Department and Course ") with One-To-Many relationship and When i only use on one side("only table Derpartment). Scenario is similar for Many-To-Many relationship as well.

My question: Should "fetch = FetchType.EAGER , cascade = CascadeType.ALL" be defined only on one side or both sides in the above mentioned scenarios ?

virteanchi
  • 169
  • 1
  • 14
  • https://stackoverflow.com/questions/5360795/what-is-the-difference-between-unidirectional-and-bidirectional-jpa-and-hibernat – guleryuz Mar 24 '19 at 05:21
  • Possible duplicate of [What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?](https://stackoverflow.com/questions/5360795/what-is-the-difference-between-unidirectional-and-bidirectional-jpa-and-hibernat) – Andronicus Mar 24 '19 at 05:36

1 Answers1

1

fetch and cascade options can be defined on both sides. If its defined only on one side that it won't have any impact when the other side object is fetched. e.g. If eager fetch is set for courses in Department class but not in Course class then, if a select query is made on department then, it will fetch all its courses along with it But if a select query is made on course then, it won't fetch its associated department unless explicitly called out in query.

Same goes for cascade option. Thus, its definition on either side depends on the kind of queries which are required to be made. If there are going to be a lot of queries on department which needs all the courses information every time but its not the same for fetching a course then, fetch option should be defined only in Department class for courses.

Bi-directional association is good but with additional update in your code for efficient queries i.e. use JoinColumn with @ManyToOne association so that additional association mapping information between two entities doesn't have to be maintained on code side.

deepak
  • 113
  • 8