Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving order of a List in JPA

Tags:

java

jpa

I have the following question about JPA:

Can I save the order of the elements in a java.util.List? In my application the order in which I put elements in the Lists is important but after I get those collections from the database the order is not the same (as expected). Can you show me a way to deal with this problem?

P.S. There is not a field in the entities that I put in the collections by which I can order them.

Rosen

like image 303
Rosen Martev Avatar asked Apr 15 '10 08:04

Rosen Martev


People also ask

How do you keep order provided in in clause in Spring data JPA?

You can do that by JPA too but you will have to create a comma separated list of ids in the order you want. In your case you can keep same order. There is also one alternative using JPQL: You can use ,,FIELD'' instead of ,,FIND_IN_SET ''.

What does@ OrderColumn do?

@OrderColumn annotation specifies a column that should maintain the persistent order of a list. The persistence provider maintains the order and also updates the ordering on insertion, deletion, or reordering of the list. This annotation can be used on @OneToMany or @ManyToMany relationship or on @ElementCollection .

What is OrderColumn JPA?

The OrderColumn annotation is specified on a OneToMany or ManyToMany relationship or on an element collection. The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered.

What does save method do in JPA?

save(…)- Method. It will persist or merge the given entity using the underlying JPA EntityManager. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.


Video Answer


1 Answers

There are some hacky ways of doing this in JPA 1, but it's easiest to switch to a JPA 2 provider. The @OrderColumn annotation support is what you're looking for. Eclipselink have an ok tutorial on how to use it.

like image 96
GaryF Avatar answered Sep 27 '22 23:09

GaryF