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.

@Entity 
public class Parent {
    @oneToMany

    private Set<Child> children;

    // More attributes
}

@Entity
public class Child {
    @ManyToOne    
    private Parent parent;    
        
        //More attributes
}

When retrieving children collection from parent entity,
parent.getChildren();

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
@OneToMany
@OrderBy
private Set<Child> children;

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

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


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...