Duplicates in OneToMany annotated List

落爺英雄遲暮 提交于 2019-12-21 21:42:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20749806/duplicates-in-onetomany-annotated-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!