Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicates in OneToMany annotated List

I'm working on a Java project using JPA 2 + Hibernate 4.2.6 and I'm getting a strange behaviour.

In my model I have two related entites: Question and Answer

@Entity
public class Question {
    // ...

    @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<Answer> answers;

    // ...
}


@Entity
public class Answer {
    // ...

    @ManyToOne(optional = false)
    @JoinColumn(name = "question_id", nullable = false)
    private Question question;

    // ...
}

This works perfectly: all Answers related to a certain Question are loaded correctly.

But now I need to change the tipe of answers collecton from Set to List. I changed the type and ran the application again and now I get several duplicates in answers... Why is it possible? I know that List allows duplicates, but there are no duplicate records in my DB, so why I get these?

I read about some similar bugs in previous version of Hibernate, but I expect they are solved in last version... am I wrong?

NOTE I need to change Set into List because I need to keep information about the order for answers and, possibly, to change this order.

like image 291
davioooh Avatar asked Dec 23 '13 19:12

davioooh


1 Answers

You are most likely getting duplicates because when using fetch=FetchType.EAGER, Hibernate uses an outer join to fetch the data in the joined table.

Try removing the eager fetching to confirm. If it is the case, you should either remove the eager fetching, keep a Set instead of a List, or write a JPQL query to retrieve exactly what you need.

From Hibernate doc:

The recommanded approach is to use LAZY on all static fetching definitions and override this choice dynamically through JP-QL.

like image 152
David Levesque Avatar answered Oct 05 '22 13:10

David Levesque