开发者

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 p开发者_JAVA技巧ossibility 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.


JPA (which hibernate implements) has @OrderBy:

@OneToMany
@OrderBy("uuidColumn")
private List<Something> list;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜