使用 Set JPA 维护 @ElementCollection 中的顺序
Maintaining Order in @ElementCollection using Set JPA
我在使用 JPA 和 Hibernate 时遇到了很多问题。最大的问题是发出了太多的查询,速度太慢了。
因此,为了反击,我已将所有关系切换为 Set,并一直在使用获取连接在一个请求中获取对象图。
结果是,我无法切换到 List 来获取一组有序的值,因为存储库在启动时抛出一个异常,即当我尝试加入超过一个实体。
所以我发现了一个名为 @OrderColumn 的新 JPA 2.0 功能 - 但我不确定如何将它应用到 ElementCollection:
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "variant_option_vals",
joinColumns = @JoinColumn(name = "variantOption_id")
@OrderColumn(name="sequence")
)
private Set<String> optionValues;
我添加了注释,但序列列被添加到基础 table,而不是选项值 table。
或者,有没有办法保持项目的自然顺序?即保持物品输入的顺序,并避免同时出现行李问题?
尝试使用 SortedSet 作为该集合的实现?
@OrderColumn
注释不能用于集合,只能用于列表。
OrderColumn documentation 文档说:
Specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.
对于集合,唯一的选择是使用 @OrderBy
注释使用实体的字段进行排序,而不是集合的插入顺序。
我在使用 JPA 和 Hibernate 时遇到了很多问题。最大的问题是发出了太多的查询,速度太慢了。
因此,为了反击,我已将所有关系切换为 Set,并一直在使用获取连接在一个请求中获取对象图。
结果是,我无法切换到 List 来获取一组有序的值,因为存储库在启动时抛出一个异常,即当我尝试加入超过一个实体。
所以我发现了一个名为 @OrderColumn 的新 JPA 2.0 功能 - 但我不确定如何将它应用到 ElementCollection:
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "variant_option_vals",
joinColumns = @JoinColumn(name = "variantOption_id")
@OrderColumn(name="sequence")
)
private Set<String> optionValues;
我添加了注释,但序列列被添加到基础 table,而不是选项值 table。
或者,有没有办法保持项目的自然顺序?即保持物品输入的顺序,并避免同时出现行李问题?
尝试使用 SortedSet 作为该集合的实现?
@OrderColumn
注释不能用于集合,只能用于列表。
OrderColumn documentation 文档说:
Specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.
对于集合,唯一的选择是使用 @OrderBy
注释使用实体的字段进行排序,而不是集合的插入顺序。