Search code examples
javajpaeclipselink

How do I guarantee the order of items in a collection


I have a list of objects and each and every object in the list have a position which may not change unless explicitly changed, in other words, the objects are in a queue. What collection should I use in my entity class to store these objects and how should that collection be annotated?

I currently have this

@Entity
class Foo {
  ...
  @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
  List<Bar> bars = new ArrayList<Bar>();
  ...
}

If this is not possible with JPA purely, I'm using EclipseLink as my JPA provider, so EclipseLink specific annotations will ok if nothing else helps.

EDIT: Note people, the problem is not that Java wouldn't preserv the order, I know most collections do, the problem is that I don't know a smart way for JPA to preserv the order. Having an order id and making the query order by it is possible, but in my case maintaining the order id is laborious (because the user interface allows reordering of items) and I'm looking for a smarter way to do it.


Solution

  • If you want this to be ordered after round-tripping to SQL, you should provide some sort of ordering ID within the entity itself - SQL is naturally set-oriented rather than list-oriented. You can then either sort after you fetch them back, or make sure your query specifies the ordering too.

    If you give the entity an auto-generated integer ID this might work, but I wouldn't like to guarantee it.