Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
Piotr Sobczyk Avatar asked May 09 '12 14:05

Piotr Sobczyk


2 Answers

You can use the Hibernate @SortComparator annotation:

Like this:

@OneToMany(mappedBy = "paramSpec", cascade = CascadeType.ALL)
@SortComparator(ReleaseComparator.class)
private List<PkdbParameter> pkdbParams;

Where CameraNameComparator is:

public class ReleaseComparator implements Comparator<PkdbParameter> {
    @Override
    public int compare(PkdbParameter o1, PkdbParameter o2) {
        return o1.getRelease().getOrdinal().compareTo( o2.getRelease().getOrdinal() );
    }
}
like image 117
Vlad Mihalcea Avatar answered Nov 12 '22 16:11

Vlad Mihalcea


@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

like image 25
anergy Avatar answered Nov 12 '22 16:11

anergy