Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: how to maintain insertion order

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.

like image 978
jwaddell Avatar asked Jun 11 '10 04:06

jwaddell


1 Answers

JPA (which hibernate implements) has @OrderBy:

@OneToMany
@OrderBy("uuidColumn")
private List<Something> list;
like image 126
Bozho Avatar answered Oct 11 '22 22:10

Bozho