简体   繁体   中英

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 WHERE (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 ...

怀疑您想输入IN而不是=,但是诸如“不能为程序提供此功能”之类的短语让我感到紧张,因为有很多被黑的东西在发生。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM