与hibernate关联的子查询

时间:2012-06-13 22:28:49

标签: java hibernate jpa hql

任何人都知道是否可以在像下面这样的查询中使用子查询?

SELECT l, o
FROM User u
    INNER JOIN u.licenses l
    LEFT JOIN l.orders o 
        WITH o.id = (
            SELECT MAX(lastOrder.id)
            FROM Order lastOrder
            WHERE lastOrder.license = l
        )
WHERE u.idtPerson = :idtPerson
    AND l.statusCode != 3

我发现了这个解决方法......

SELECT l, o
FROM User u
    INNER JOIN u.licenses l
    LEFT JOIN l.orders o
WHERE u.idtPerson = :idtPerson
    AND l.statusCode != 3
    AND (
        o.id IS NULL
        OR o.id = (
            SELECT MAX(lastOrder.id)
            FROM Order lastOrder
            WHERE lastOrder.license = l
        )
    )

但我真的相信这不是一个好的解决方案,有什么建议吗?

1 个答案:

答案 0 :(得分:0)

另一个选项是在另一个查询中创建子查询,使用maxresults = 1列出它,并将其按参数传递给原始查询。

这样的事情:

Query hqlQuery = session.createQuery("SELECT MAX(lastOrder.id)
                                      FROM Order lastOrder
                                      WHERE lastOrder.license = l");    
hqlQuery.setMaxResults(1);
List results = hqlQuery.list();
Integer maxId = null;
if (!results.isEmpty()){
   maxId = results.get(0);
}
Query hqlQuery1 = session.createQuery("SELECT l, o
                                       FROM User u
                                       INNER JOIN u.licenses l
                                       LEFT JOIN l.orders o 
                                       WITH o.id = :maxId
                                       WHERE u.idtPerson = :idtPerson
                                       AND l.statusCode != 3");
hqlQuery1.setParameter("maxId", maxId);
hqlQuery1.list();
...etc...

也许这对你有用