Hibernate @OrderBy for nested properties

Piotr Sobczyk picture Piotr Sobczyk · May 9, 2012 · Viewed 8.3k times · Source

I need to use @OrderBy (JPA, Hibernate as provider) to sort collection for nested property:

@OneToMany(mappedBy = "paramSpec", cascade = CascadeType.ALL)
@OrderBy("release.ordinal")
private List<PkdbParameter> pkdbParams;

In PkdbParameter.java:

...
@ManyToOne
@JoinColumn(name = "release_id")
private Release release;
...

In Release.java:

...
private int ordinal;
...

(all of these fields have simple getters and setters provided)

Unfortunately I'm getting error:

Caused by: org.hibernate.AnnotationException: property from @OrderBy clause not found: some.package.PkdbParameter.release.ordinal

What's wrong with this code? If it's impossible to use nested properties notation is there any other way to order for ordinal property?

Answer

anergy picture anergy · Mar 22, 2013

@OrderBy works only with direct properties or embedded attributes. From Java EE 6 docs

The dot (".") notation is used to refer to an attribute within an embedded attribute

So if the Release is an embedded attribute, this could work. Otherwise you could use named query as suggested here