Hibernate: @OrderBy vs @OrderColumn to maintain the order of a collection

前端 未结 1 1568
说谎
说谎 2020-12-24 15:02

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

相关标签:
1条回答
  • 2020-12-24 15:32

    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:

    • if you explicitely call session.save(), of session.saveOrUpdate(), this assigns an ID to the entity, so calling it for b1, b2 and b3 will respect the order
    • AFAIK, all the other methods (cascading, merge(), persist()) don't guarantee any order (except if you merge or persist, and then flush())

    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.

    0 讨论(0)
提交回复
热议问题