Monday, March 18, 2013

How to order child collection in JPA

Assume there are 2 entities, Parent and Child
In many cases, children collection are directly retrieve from parent entity without writing additional query.
But there is a problem to retrieve children collection directly from parent entity -- the children collection are in an unsorted manner.
This problem could be solved by adding the @OrderBy annotation.

public class Parent {

    private Set<Child> children;

    // More attributes

public class Child {
    private Parent parent;    
        //More attributes

When retrieving children collection from parent entity,

it is in an unsorted manner.
to sort the children collection, simply add the @orderBy annotation on top of the children collection.

Default sort by primaryKey
private Set<Child> children;

Sort by child's property
@OrderBy( propertyInChildEntity )
private Set<Child> children;

Sort by child's property, ascending or descending
@OrderBy( propertyInChildEntity ASC|DESC)
private Set<Child> children;


No comments:

Post a Comment


Related Posts Plugin for WordPress, Blogger...