33

I have the following question about 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?

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

Rosen

Rosen Martev
  • 519
  • 1
  • 6
  • 13

3 Answers3

40

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.

GaryF
  • 23,950
  • 10
  • 60
  • 73
  • Is this annotation only available in eclipselink? Anyway as far as I can see it will not solve my problem. In the example in the link you gave the order in which the entities are added in the table is saved, not the order in which they are met in a collection. Like they are ordered by the ID-s of the "phone" entities. It is not my case. P.S. One entity may be part of a different count of collections. – Rosen Martev Apr 15 '10 at 09:10
  • 1
    It's not just part of Eclipselink, no, it's part of the JPA 2 specification. I've not used it myself yet, but it should preserve the order of the collection. Another link: http://blogs.sun.com/ldemichiel/entry/java_persistence_2_0_public – GaryF Apr 15 '10 at 13:35
  • You can thank Oracle for that. Looks like they've moved it to their own infrastructure without a redirect. New url is: https://blogs.oracle.com/ldemichiel/entry/java_persistence_2_0_public – GaryF Mar 25 '12 at 15:32
  • Hours of working with entity lifecycle callbacks... Problem solved instantaneously with this solution. – Mordechai Jan 16 '17 at 02:58
3

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.

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

Ujwal Daware
  • 373
  • 5
  • 18
3

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.

JDO has had indexed lists since day 1

DataNucleus
  • 15,497
  • 3
  • 32
  • 37