JPQL: Problem with the following WHERE-Clause using Inheritance
I'm using the following query, for getting all Fruits that are linked with the User.
return (List<Fruit>) getEm()
.createQuery(
"SELECT DISTINCT f FROM Fruit f, User u WHE开发者_运维问答RE (f = u.apples OR f = u.oranges OR f = u.mangos) AND u.id = :id")
.setParameter("id", id).getResultList();
The corresponding Entities are the following:
public class Fruit{
private int id;
}
public class User{
private int id;
private Collection<Apple> apples;
private Collection<Orange> oranges;
private Collection<Mango> mangos;
}
public class Mango extends Fruit{
private int id;
...
}
public class Apple extends Fruit{
private int id;
...
}
public class Orange extends Fruit{
private int id;
...
}
The problem is, that the above mentioned query dont give me a result if any of the Collections dont exist for the user. So if a user has no apples, i dont get 0 as the result. I already tried to catch errors with statements like u.apples IS NOT EMPTY, etc. but it doenst work either.
So, could you give me a tipp for this case? The whole thing would be easier, if the Fruit would have a one-to-many relation to the user, but unfortunatelly i cant afford this for the program...
Thanks in advance!
Your JPQL is not valid, so I'm not sure how it works at all.
You can only use the "." notation on a ToOne not a ToMany, for a ToMany you need to use a join. For a join you can use an outer join to allow none.
SELECT DISTINCT f FROM Fruit f, User u left join u.apples a ... WHERE f = a or ...
Suspect you want IN and not =, but phrases like "cant afford this for the program" make me nervous that there's a lot of hacked stuff going on.
精彩评论