6

I have a class say: "ClassA" which has a collection of "ClassB"

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "COLUMN_NAME")    
private List<ClassB> lotsOfClasses;

"ClassB" has a mapped class "ClassC" using plain old mapping annotations:

public class ClassB {
...
  @ManyToOne
  @JoinColumn(name="AD_POINT_ID")
  private ClassC classC;
...
}

How do I add an @OrderBy annotation to ClassA's collection to ClassB, so that the collection is ordered by the "name" property of ClassC

Like so:

@OrderBy(clause="classC.name asc")

All I get are Oracle exceptions saying that classC is unknown.

Any help here would be awesome, as its really bugging me at the moment.

P.S. I should also mention that using the OrderBy annotation on the collection like this: @OrderBy(clause="classC asc") (i.e. without the .name on classC) I get a valid SQL statement, which uses the ID column (the primary key) of classC to order by.

Cheers, Mark

Mark
  • 14,820
  • 17
  • 99
  • 159
  • As suggested by Jiří Vypědřík you can implement java.util.Comparator interface. In the implemented compare method you can implement the logic to refer to the Hibernate Mapped object without problem, and return the int value accordingly. However this will not utilize the ordering on the Oracle DB but in-memory (JVM) sorting instead. – retromuz Apr 30 '13 at 14:44

4 Answers4

8

It's unfortunately impossible to do what you want. I've answered a similar question here.

@OrderBy only supports direct properties of the collection elements.

Community
  • 1
  • 1
ChssPly76
  • 99,456
  • 24
  • 206
  • 195
3

use @Sort with custom comparator instead

Jiří Vypědřík
  • 1,324
  • 12
  • 24
1

This is possible if you use JPA. See this article.

Then you just add @OrderBy("name") to the collection property

Atle
  • 446
  • 6
  • 18
0

I only know NHibernate (.NET version), but I guess it should work similar:

@OrderBy(clause = "name asc")  

Or you can try this:

@OrderBy("name")  
Enyra
  • 17,542
  • 12
  • 35
  • 44
  • But that would be the 'name' property of ClassB, I need the name property of ClassC – Mark Jun 24 '09 at 22:25