Hibernate的CollectionOfElements预先抓取重复元素 [英] Hibernate CollectionOfElements EAGER fetch duplicates elements

查看:228
本文介绍了Hibernate的CollectionOfElements预先抓取重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为SynonymMapping类具有映射为CollectionOfElements值的集合

I have a class called SynonymMapping which has a collection of values mapped as a CollectionOfElements

@Entity(name = "synonymmapping")
public class SynonymMapping {

    @Id private String keyId;

    //@CollectionOfElements(fetch = FetchType.EAGER)
    @CollectionOfElements
    @JoinTable(name="synonymmappingvalues", joinColumns={@JoinColumn(name="keyId")})
    @Column(name="value", nullable=false)
    @Sort(type=SortType.NATURAL)
    private SortedSet<String> values;

    public SynonymMapping() {
    	values = new TreeSet<String>();
    }

    public SynonymMapping(String key, SortedSet<String> values) {
    	this();
    	this.keyId = key;
    	this.values = values;
    }

    public String getKeyId() {
    	return keyId;
    }

    public Set<String> getValues() {
    	return values;
    }
}

我有一个测试,我用两个SynonymMapping对象存储到数据库,然后查询数据库,返回所有保存SynonymMapping对象,指望我存储在两个对象。

I have a test where I store two SynonymMapping objects to the database and then ask the database to return all saved SynonymMapping objects, expecting to receive the two objects I stored.

当我更改值的映射渴望(如被注释掉线code所示),并再次运行测试,我收到四场比赛。

When I change the mapping of values to be eager (as shown in in the code by the commented out line) and run the test again, I receive four matches.

我已经清除了运行的数据库,我可以复制这个问题渴望和懒惰之间交换。

I have cleared out the database between runs and I can duplicate this problem swapping between eager and lazy.

我觉得它与加入的话Hibernate创建下面,但我不能在网上找到一个明确的答案的事情。

I think it has to do with the joins that hibernate creates underneath but I can't find a definite answer online.

谁能告诉我,为什么一个预先抓取被复制的对象?

Can anyone tell me why an eager fetch is duplicating the objects?

感谢。

推荐答案

这是一般不执行急于在映射取一个好主意 -​​ 这是更好地指定相应的查询渴望加入(除非你是100%肯定下任何和你的对象将没有意义/是不被填充该集合所有有效的情况下)。

It's generally not a good idea to enforce eager fetching in the mapping - it's better to specify eager joins in appropriate queries (unless you're 100% sure that under any and all circumstances your object won't make sense / be valid without that collection being populated).

你得到重复的原因是因为Hibernate内部加入你的根和收集表。请注意,他们真的是重复的,例如2 SynonymMappings 3个集合元素每次你会得到6个结果(2×3),每个SynonymMapping实体的3份。因此最简单的解决办法是包装在一个集从而确保他们是唯一的结果。

The reason you're getting duplicates is because Hibernate internally joins your root and collection tables. Note that they really are duplicates, e.g. for 2 SynonymMappings with 3 collection elements each you would get 6 results (2x3), 3 copies of each SynonymMapping entity. So the easiest workaround is to wrap results in a Set thereby ensuring they're unique.

这篇关于Hibernate的CollectionOfElements预先抓取重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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