2020-06-28

Hibernate JPA @OrderBy Example

@OrderBy

The @OrderBy annotation is used to specify a SQL ordering directive for sorting the currently annotated collection.

It differs from the JPA @OrderBy annotation because the JPA annotation expects a JPQL order-by fragment, not an SQL directive.

OrderBy
Order a collection using SQL ordering (not HQL ordering). Different from OrderBy in that this expects SQL fragment, JPA OrderBy expects a valid JPQL order-by fragment.

Customizing ORDER BY SQL clause
While the JPA @OrderBy annotation allows you to specify the entity attributes used for sorting when fetching the current annotated collection, the Hibernate specific @OrderBy annotation is used to specify a SQL clause instead.

In the following example, the @OrderBy annotation uses the CHAR_LENGTH SQL function to order the Article entities by the number of characters of the name attribute.

Example : @OrderBy mapping example

@Entity(name = "Person")
public static class Person {

@Id
private Long id;

private String name;

@OneToMany(
mappedBy = "person",
cascade = CascadeType.ALL
)
@org.hibernate.annotations.OrderBy(
clause = "CHAR_LENGTH(name) DESC"
)
private List<Article> articles = new ArrayList<>();

//Getters and setters are omitted for brevity
}

@Entity(name = "Article")
public static class Article {

@Id
@GeneratedValue
private Long id;

private String name;

private String content;

@ManyToOne(fetch = FetchType.LAZY)
private Person person;

//Getters and setters are omitted for brevity
}

No comments:

Post a Comment