Java @OneToMany List<> vs Set<> 区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6562673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:46:12  来源:igfitidea点击:

@OneToMany List<> vs Set<> difference

javajpa

提问by M4ks

Is there any difference if I use

如果我使用有什么区别吗

@OneToMany
public Set<Rating> ratings;

or if I use

或者如果我使用

@OneToMany
public List<Rating> ratings;

both work OK, i know difference between list and a set, however I don't know if this makes any difference how hibernate (or rather JPA 2.0) handles it.

两者都可以正常工作,我知道列表和集合之间的区别,但是我不知道这是否对休眠(或更确切地说 JPA 2.0)的处理方式有任何影响。

采纳答案by JB Nizet

A list, if there is no index column specified, will just be handled as a bag by Hibernate (no specific ordering).

一个列表,如果没有指定索引列,将被 Hibernate 当作一个包处理(没有特定的排序)。

One notable difference in the handling of Hibernate is that you can't fetch two different lists in a single query. For example, if you have a Personentity having a list of contacts and a list of addresses, you won't be able to use a single query to load persons with all their contacts and all their addresses. The solution in this case is to make two queries (which avoids the cartesian product), or to use a Setinstead of a Listfor at least one of the collections.

处理 Hibernate 的一个显着区别是您不能在单个查询中获取两个不同的列表。例如,如果您有一个Person包含联系人列表和地址列表的实体,您将无法使用单个查询来加载人员及其所有联系人和地址。这种情况下的解决方案是进行两次查询(避免笛卡尔积),或者对至少一个集合使用 aSet而不是 a List

It's often hard to use Sets with Hibernate when you have to define equalsand hashCodeon the entities and don't have an immutable functional key in the entity.

当您必须在实体上定义equals和 并且hashCode实体中没有不可变的功能键时,通常很难将 Set 与 Hibernate 一起使用。

回答by Basanth Roy

If you use a List, then you can specify an 'Order BY' clause in getter function. You can't do that with a Set. The order by clause can contain partial EJBQL; For example

如果使用 List,则可以在 getter 函数中指定“Order BY”子句。你不能用 Set 做到这一点。order by 子句可以包含部分 EJBQL;例如

@OneToMany
@OrderBy("lastname ASC")
public List<Rating> ratings;

If you leave this field blank, then the list is sorted in ascending order based on the value of the primary key.

如果将此字段留空,则列表将根据主键的值按升序排序。