My data model is made of Schools and Students. Students have a FK to the School they belong to. I do not understand why the collection contains duplicates, i.e. Joe, Joe, Mary, Mary, Tom, Tom, etc The SQL query generated by Hibernate is correct and does not return duplicates. I could implement a hack to filter out duplicates, but I am not ready to live with a broken window yet ;) I have tried to paste the relevant pieces of code below. Any help greatly appreciated!
// SchoolJpa
@OneToMany (
mappedBy = "school",
targetEntity = StudentJpa.class,
fetch = FetchType.LAZY,
cascade = CascadeType.ALL
)
@Override
public List<Student> getStudentsInternal() {
return super.getStudentsInternal();
}
// SchoolImpl
private List<Student> students = new ArrayList<Student>();
public List<Student> getStudents() {
return Collections.unmodifiableList(students);
}
public List<Student> getStudentsInternal() {
return students;
}
public void setStudentsInternal(List<Students> students) {
this.students = students;
}
My guess is that you have a FetchType.EAGER or other mapping in School which will cause an outer join query to be issued by Hibernate, which will result in duplicates in the list.
Switching types to SET works because a set naturally de-dupes based on equality, so the duplicates returned by the outer join query are lost.
A much more thorough explanation by Eran Medan available here:
Hard to say from the piece of code but:
equals
/hashCode
properly anyway (I suspect a problem at this level).Actually, can you show the whole mappings? I'm not sure to understand why you have several getters and setters on the same field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With