JPA/hibernate sorted collection @OrderBy vs @Sort

前端 未结 3 1070
深忆病人
深忆病人 2020-12-23 09:55

I would like to have a collection of child objects (here cat-kitten example) that are ordered. And keep their order on adding of new elements.

@Entity 
publ         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 10:22

    The latest version of Hibernate uses new annotations to accomplish this:

    @SortNatural
    @OrderBy("name ASC")
    private SortedSet kittens = new TreeSet<>();
    

    There are two parts to this:

    1. The @OrderBy annotation specifies that an order by clause should be added to the database query when fetching the related records.
    2. The @SortNatural annotation assumes that Kitten implements the Comparable interface and uses that information when constructing the TreeSet instance. Note that you can replace this with the @SortComparator annotation, which allows you to specify a Comparator class that will be passed to the TreeSet constructor.

    See documentation: https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#collections-sorted-set

提交回复
热议问题