KCL
KCL

Reputation: 6873

Defining the order of a list

I have the following problem. I have three classes, A, B and C. A contains a OneToMany relationed list of B:s. B contains a ManyToOne relation to C. C contains a field called "name" and B also contains a field called "name". What I'd like to accomplish is to have the items in A's list sorted primarily by C's name and secondarily by B's name - the problem is that I do not know how to do this. Is it even possible?

I'm using EclipseLink as my JPA provider.


class A {
   @OneToMany
   @OrderBy("b.c.name, b.name") <---- this is the problem
   List<B> b;
}

class B {
   @ManyToOne
   C c;
   String name;
}

class C {
   String name;
}

EDIT Yes, I've tried different variations, for example @OrderBy("c.name") doesn't work, I just get an error message telling me that the entity class b does not contain a field called "c.name".

Upvotes: 10

Views: 8445

Answers (5)

evg345
evg345

Reputation: 107

It is not possible in javax.persistence.OrderBy (as say ChssPly76 ), but when I was using Hibernate I construct new column in PLAIN SQL with Formula() annotation and then OrderBy over it:

class A {
   @OneToMany
   @OrderBy("orderCol") <---- reference to virtual column
   List<B> b;
}

class B {
   @ManyToOne
   C c;
   String name;

   @org.hibernate.annotations.Formula(
     "( select C_table.name as orderCol from C_table where C_table.id = id )"
   ) <------------------------------------------ join with plain SQL statment
   String orderCol;
}

May be EclipseLink has same possibilities?

Upvotes: 0

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

ChssPly76 is right.

What you could do is to create a named query like this one:

 SELECT b 
 FROM B b 
 WHERE b.a = :mya 
 ORDER BY b.c.name

Upvotes: 3

ChssPly76
ChssPly76

Reputation: 100706

It's NOT possible. @OrderBy only accepts direct property / field names, not nested properties. Which makes sense, really, because "c" table - depending on your fetching strategy may not even be part of a select issued to retrieve your "b"s.

Upvotes: 13

Jack Leow
Jack Leow

Reputation: 22477

Have you tried:

 @OrderBy("c.name ASC", "name ASC")

?

Upvotes: 0

Chochos
Chochos

Reputation: 5159

Have you tried @OrderBy("c.name", "name") ?

You shouldn't use "b." because it's implied that the @OrderBy will be done on columns of the instances of B on the b array.

Upvotes: 0

Related Questions