tags:

views:

123

answers:

2

I have a list of entities where creation order is important, but they do not contain a timestamp to use for sorting. Entities are added to the end of the list as they are created so they will be ordered correctly in the list itself.

After persisting the list using Hibernate the entities appear in the database table in the order that they were created. However when retrieving the list using a new Hibernate session the list is now in reverse order of insertion/creation.

Is this expected behaviour? Is there any way to retrieve the list in the same order as it appears in the table?

The primary key is a UUID, and the list of entities should always have been created on the same IP address and JVM. This mean sorting by UUID is a possibility but I'd rather not make assumptions.

Another possibility is if the list is guaranteed to always come out in reverse order I could always just work through it backwards.

+1  A: 

You have to persist the list as a list. This way, you will have an extra column to save the order of the elements.

Types such as bags and sets will get the job done, but will lose the order of elements.

mcabral
I'm already using a list, but sounds like I'd need to add an index column to the database to make it work properly (I'm using annotations to define the entities). Ideally I'd like to avoid making any changes to the database structure, is there any way to do so?
jwaddell
Have you tried the @OrderColumn annotation? http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/ under the 'Indexed Collections' section? If this work let me know so i can update my answer :)
mcabral
+2  A: 

JPA (which hibernate implements) has @OrderBy:

@OneToMany
@OrderBy("uuidColumn")
private List<Something> list;
Bozho
I ended up doing this and relying on the fact that Hibernate produces UUIDs which can be sorted by the time they were created, as long as they were created on the same JVM on the same IP address.
jwaddell