java - Hibernate SET 元素 order-by 子句

标签 java hibernate

我想知道,当 fetch=select 时,您可以在映射文件中的 SET 元素上设置 order-by 属性,但如果您在创建询问。这样会安全吗?

我的意思是,他们正在将结果抽取到 HashSet 中,我不是认为它们不能保证元素顺序吗?

最佳答案

Hibernate 实际上不会将结果泵入 HashSet , 它将替换任何现有的 HashSet有自己的实现 Set .

When you make the instance persistent, by calling persist(), Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set.

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html

如果您使用 order-by 属性,那么它不会使用 HashSet , 可能会使用 LinkedHashSet反而。请引用我在上面引用的同一文档中的内容:

If you want the database itself to order the collection elements, use the order-by attribute of set, bag or map mappings. This solution is implemented using LinkedHashSet or LinkedHashMap and performs the ordering in the SQL query and not in the memory.

因此 Hibernate 将安全地维护 Set 中的项目顺序——但是当你创建新对象并持久化它们时要小心。如果您使用 HashSet而不是 LinkedHashSet在一个新对象中,那么 Hibernate 将以基本上随机的顺序保留你的集合,因为 HashSet不保证元素顺序。

关于java - Hibernate SET 元素 order-by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7303170/

相关文章:

java - 无法将连接转换为 oracle.jdbc.OracleConnection

database - 即使数据库失败如何运行 Spring Boot 应用程序

java - 建议使用 Mongo 将数据存储在 hashmap 中

java - Spring Data JPA - 如何将查询结果转换为实体类

Java 将函数传递给方法

java - Hibernate 数据源与 JNDI 的连接

hibernate - 如何控制 Hibernate 的日志记录?

hibernate 多对一与一对一

java - 从命令行运行 Spring Boot 应用程序时出错

java - 如何并行调用返回 future 的方法?