在OneToMany注释列表中重复 [英] Duplicates in OneToMany annotated List

查看:502
本文介绍了在OneToMany注释列表中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA 2 + Hibernate 4.2.6的Java项目,我得到一个奇怪的行为。



在我的模型中,我有两个相关entites:问题回答

 code> @Entity 
public class Question {
// ...

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

// ...
}


@Entity
public class Answer {
// ...

@ManyToOne(optional = false)
@JoinColumn(name =question_id,nullable = false)
private问题;

// ...
}

$


$ b $ b

但现在我需要更改答案 collecton从设置列表。我改变了类型,并再次运行应用程序,现在我得到几个重复的答案 ...
为什么可能?我知道列表允许重复,但是在我的数据库中没有重复的记录,所以为什么我得到这些?



我读了一些类似的bug,在以前的版本的Hibernate,但我期望他们在最后的版本中解决...我错了吗?



strong>我需要更改设置为列表,因为我需要保存有关订单

你最有可能得到重复,因为当使用fetch = FetchType时。 EAGER,Hibernate 使用外连接以获取连接表中的数据。



尝试删除热门抓取以确认。如果是这样,你应该删除渴望的提取,保持Set而不是列表,或者写一个JPQL查询来准确地检索你需要的。



Hibernate doc


推荐的方法是在所有静态获取
定义中使用LAZY,并通过JP-QL动态覆盖此选项。



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.

解决方案

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.

这篇关于在OneToMany注释列表中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆