KCL
KCL

Reputation: 6883

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.

Upvotes: 1

Views: 3734

Answers (5)

Mark S
Mark S

Reputation: 61

Use a sort order id, as Jon suggested, then add an @OrderBy annotation below the @OneToMany. This will order any query by the specified field.

As an example, if you add a new field called "sortId" to Bar, Foo would look like this:

@Entity
class Foo {
  ...
  @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
  @OrderBy("sortId ASC")
  List bars = new ArrayList();
  ...
}

Upvotes: 4

Vlad Gudim
Vlad Gudim

Reputation: 23502

It's worth trying LinkedList instead of ArrayList, however, as Jon said, you need to find a way of persisting the order information.

A solution will probably involve issuing an order number to each entry an storing it as a SortedMap, when converting into the List, if List is that you need.

However, ORM could potentially be clever enough to do all the conversions for you if you stored the collection as LinkedList.

Upvotes: 0

Omar Kooheji
Omar Kooheji

Reputation: 55800

A linked list implements the Queue inteface in java and allows you to add things in the middle...

TBH most of the collections are ordered aren't they...

Check the docs, most say whether or not they are ordered.

Upvotes: 0

Fortyrunner
Fortyrunner

Reputation: 12792

You can

  1. Sort a List before creation
  2. Sort a List after creation
  3. Use a collection that performs a sort on insert. TreeMap, TreeSet

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503489

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.

Upvotes: 4

Related Questions