Java 在 JPA 中保存列表的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2643641/
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-13 10:16:42  来源:igfitidea点击:

Saving order of a List in JPA

javajpa

提问by Rosen Martev

I have the following question about JPA:

我有以下关于 JPA 的问题:

Can I save the order of the elements in a java.util.List? In my application the order in which I put elements in the Lists is important but after I get those collections from the database the order is not the same (as expected). Can you show me a way to deal with this problem?

我可以在 java.util.List 中保存元素的顺序吗?在我的应用程序中,我将元素放入列表中的顺序很重要,但是在我从数据库中获取这些集合后,顺序就不一样了(如预期的那样)。你能告诉我处理这个问题的方法吗?

P.S. There is not a field in the entities that I put in the collections by which I can order them.

PS 在我放入集合的实体中没有一个字段,我可以通过它来订购它们。

Rosen

罗森

采纳答案by GaryF

There are some hacky ways of doing this in JPA 1, but it's easiest to switch to a JPA 2 provider. The @OrderColumn annotation support is what you're looking for. Eclipselink have an ok tutorial on how to use it.

在 JPA 1 中有一些执行此操作的hacky 方法,但最容易切换到 JPA 2 提供程序。@OrderColumn 注释支持正是您所需要的。Eclipselink 有一个关于如何使用它的不错的教程

回答by DataNucleus

JPA has 2 types of Lists. In JPA1 there is an "ordered list" (which is what you see, ordering defined by some SQL clause). In JPA2 you can have "ordered lists" or alternatively "indexed lists" (where the order of creation is preserved) ... the @OrderColumn referred to. Any implementation of JPA2 will have to support this e.g DataNucleus.

JPA 有两种类型的列表。在 JPA1 中有一个“有序列表”(这是你看到的,由一些 SQL 子句定义的排序)。在 JPA2 中,您可以拥有“有序列表”或“索引列表”(其中保留创建顺序)......引用的 @OrderColumn。JPA2 的任何实现都必须支持这一点,例如 DataNucleus。

JDO has had indexed lists since day 1

JDO 从第一天起就有索引列表

回答by Ujwal Daware

You can save the order of the elements in a java.util.List. In JPA 2.0, There is the good way to save the order of element by using @OrderColumn annotation.

您可以将元素的顺序保存在 java.util.List 中。在 JPA 2.0 中,有一个使用 @OrderColumn 注释来保存元素顺序的好方法。

For the details, you can refer this link Order Column (JPA 2.0)

详情可以参考这个链接 Order Column (JPA 2.0)