What is the preferred way for maintaining the order of a collection while persisting and also while retrieving from database?
I know that @OrderBy is more of a in-me
OrderBy adds an order by clause to the generated SQL to order the members of the retrieved collection by a column of the table of the target entity:
@OrderBy("lastname ASC")
public List<Student> students;
will generate a SQL query like
select ... order by student.lastname ASC
OrderColumn defines the name of an additional column in the table, containing the index of the entity in the list. If you change the ordering of the elements in the list, Hibernate will change the value of this column. And if your students have 0, 3, and 5 as values in this column, the list will be
[student0, null, null, student3, null, student5]
This is well described in the javadoc of those 2 annotations.
EDIT:
The order in which B identifiers are assigned depends on how you persist these B instances:
session.save()
, of session.saveOrUpdate()
, this assigns an ID to the entity, so calling it for b1, b2 and b3 will respect the orderflush()
)So if you want the list to hold b1, b2 and b3 in this order, regardless of the way those are persisted, your best bet is to add an @OrderColumn
annotation to the collection. Hibernate will automatically populate this column with 0 for b1, 1 for b2 and 2 for b3. And when you'll reload the parent entity, They will be in the same order in the list.