CodeScale
CodeScale

Reputation: 3314

JPA - OrderBy required with SortedSet

Why SortedSet relationship required sorting annotions like hibernate-specific @SortNatural or @OrderBy ?

Could be great if natural ordering was used by default.

Upvotes: 0

Views: 2287

Answers (1)

Paulo Araújo
Paulo Araújo

Reputation: 569

As defined in chapter 2.2 of JPA-2.2 (JSR-338):

Collection-valued persistent fields and properties must be defined in terms of one of the following collection-valued interfaces regardless of whether the entity class otherwise adheres to the JavaBeans method conventions noted above and whether field or property access is used: java.util.Collection, java.util.Set, java.util.List, java.util.Map. The collection implementation type may be used by the application to initialize fields or properties before the entity is made persistent. Once the entity becomes managed (or detached), subsequent access must be through the interface type.

Then, when retrieving data to an @OneToMany mapped field, a persistence provider implementation may use any corresponding implementation class for the given field. So, if a mapped entity defines a @OneToMany List, the persistence provider may assign the field with an ArrayList or any other concrete implementation of list, ordered or not. For interfaces not mentioned, the persistence provider may accept the mapping, but it is not required to respect it and there are no guarantees about the implementation used.

The @SortNatural proprietary annotation instructs Hibernate to use an ordered implementation of the collection type that will use the "natural comparator" of the entity to order the elements. If the contained entity type implements Comparable interface, that comparator will be the "natural" comparison method to order the given collection.

Be aware that some persistence provider implementations may or may not reuse the instantiated field to populate the collection, so, if you declared and instantiated the field with a given ordered implementation for the List or Set, it may be already ordered despite the lack of use of a hibernate-specific annotation.

The @OrderBy annotation, on the other hand, is provider agnostic and defines an order that must be respected on the retrieved list or set, but it's implementation is limited by how the database will order the field. The retrieved collection may use any implementation that preserves the order in which the data came from the database, but does not use the Comparable interface to reorder data after retrieval, as @SortNatural would.

Both approaches have their strength and hiccups, so you have to verify your use case and decide if this ordering is critical to the point of relieving it to your data layer.

Upvotes: 2

Related Questions