Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @OrderBy with referenced class

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

like image 658
Mark Avatar asked Jun 24 '09 07:06

Mark


People also ask

How to sort in Hibernate criteria?

Setting the Sorting Order. The Order class has two methods to set the sorting order: asc(String attribute) : Sorts the query by attribute in ascending order. desc(String attribute) : Sorts the query by attribute in descending order.

What is the difference between sorted and ordered collection in Hibernate?

When use sorting, Hibernate will load the associated Book entities from the database and use a Java Comparator to sort them in memory. That is not a good approach for huge Sets of entities. Ordering uses an ORDER BY clause in the SQL statement to retrieve the entities in the defined order.

What is @OrderColumn?

The OrderColumn annotation is specified on a OneToMany or ManyToMany relationship or on an element collection. The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered.

How many attributes are there in column annotation?

The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table.


1 Answers

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.

like image 137
ChssPly76 Avatar answered Sep 29 '22 06:09

ChssPly76