java - JPA - SortedSet 需要 OrderBy

标签 java hibernate jpa collections

为什么 SortedSet 关系需要排序注释,例如 hibernate 特定的 @SortNatural@OrderBy

如果默认使用自然排序,那就太好了。

最佳答案

如 JPA-2.2 ( JSR-338 ) 第 2.2 章中所定义:

Collection-valued persistent fields and properties must be defined in terms of one of the following collection-valued interfaces regardless of whether the entity class otherwise adheres to the JavaBeans method conventions noted above and whether field or property access is used: java.util.Collection, java.util.Set, java.util.List, java.util.Map. The collection implementation type may be used by the application to initialize fields or properties before the entity is made persistent. Once the entity becomes managed (or detached), subsequent access must be through the interface type.

然后,当将数据检索到 @OneToMany 映射字段时,持久性提供程序实现可以使用给定字段的任何相应的实现类。因此,如果映射实体定义了 @OneToMany 列表,则持久性提供程序可以使用 ArrayList 或列表的任何其他具体实现(有序或非有序)分配该字段。对于未提及的接口(interface),持久性提供者可以接受映射,但不需要遵守它,并且对所使用的实现没有保证。

@SortNatural 专有注释指示 Hibernate 使用集合类型的有序实现,该实现将使用实体的“自然比较器”来对元素进行排序。如果包含的实体类型实现 Comparable 接口(interface),则该比较器将是对给定集合进行排序的“自然”比较方法。

请注意,某些持久性提供程序实现可能会或可能不会重用实例化字段来填充集合,因此,如果您使用 List 或 Set 的给定有序实现声明并实例化该字段,则尽管缺少使用 hibernate 特定的注释。

另一方面,@OrderBy 注释与提供者无关,并定义在检索的列表或集合上必须遵守的顺序,但它的实现受到数据库对字段排序的方式的限制。检索到的集合可以使用任何保留数据来自数据库的顺序的实现,但不使用 Comparable 接口(interface)在检索后对数据重新排序,如 @SortNatural 那样。

这两种方法都有其优点和缺点,因此您必须验证您的用例并确定此顺序对于将其转移到数据层而言是否至关重要。

关于java - JPA - SortedSet 需要 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080580/

相关文章:

java - 使用递归的斐波那契数

java - 如何使用 JPA 和 Hibernate 删除带有 JOIN 的实体

java - JPA 如何创建具有 ManytoOne 关系的查询?

java - 将 CascadeType.MERGE 与 Spring Data Repositories 一起使用的正确方法是什么?

java - 如何在不发送回复的情况下测试异步顶点事件总线处理程序

java - 构造运行时要调用的方法名称

java - 嵌入关系

java - Hibernate 多对一更新外键为空

hibernate - Hibernate写冲突

java - 如何在 Selenium 中将 LI 与 UL 分开