Hibernate @OrderBy for nested properties

I need to use @OrderBy (JPA, Hibernate as provider) to sort the collection for a 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 these fields have simple getters and setters)

Sorry, I get an error message:

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

What is wrong with this code? If you cannot use nested property notation, is there another way to order an ordinal property?

+8
java orm hibernate jpa hibernate-mapping
source share
3 answers

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

The dotted (".") Notation is used to indicate an attribute within an inline attribute

So, if Release is a built-in attribute, this might work. Otherwise, you can use a named query as suggested here

+3
source share

You can use the Hibernate @SortComparator annotation:

Like this:

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

Where is CameraNameComparator:

 public class ReleaseComparator implements Comparator<PkdbParameter> { @Override public int compare(PkdbParameter o1, PkdbParameter o2) { return o1.getRelease().getOrdinal().compareTo( o2.getRelease().getOrdinal() ); } } 
+2
source share

You can separate the order operators and place them on non-collection properties:

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

and

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

As a side effect, you have a fixed sort order for PkdbParameter.

0
source share

All Articles