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
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 ''.
@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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With