Search code examples
javahibernatejpaormhibernate-mapping

Hibernate @OrderBy for nested properties


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?


Solution

  • @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