如何计算Hibernate JPQL中一对多连接查询中的不同项目总数?

时间:2018-03-27 15:45:54

标签: java hibernate db2 hql jpql

我无法获得" one"的总数。 hibernate HQL / JPQL中一对多连接查询的一面。

我尝试加入的两个表格(我无法控制且无法更改)看起来像这样:

House:
PK FK: owner_id
PK: town
PK: state
PK FK: inspection_id

Car:
PK FK: owner_id
PK: town
PK: state
PK: vin 

拥有者可以拥有许多房屋和许多汽车,但一辆汽车只能在一个房子里停车。所以房子和汽车之间的关系是一对多的。我尝试运行的查询看起来像这样

entityManager.createQuery(
    "select count(distinct h) " + // also tried "select count(*)", but that counts cars per garage for some reason.
    "from House h, Car c " +
    "where h.owner.id = c.owner.id " +
    "and h.town = c.town " +
    "and h.state = c.state " +
    "and h.inspection_id between 1 and 10 " +
    "and c.vin between 12345 and 23456 " +
    "group by h, c",
Long.class).getSingleResult().intValue();

但是当我尝试对DB2数据库运行此查询时,我收到错误。显然,distinct关键字在db2中不起作用。但我这样做是否正确?有没有其他方法可以用JPQL实现这一目标?

为什么我在更换时会得到每个房屋的车辆清单?#34;不同的h"用" *"?

任何帮助将不胜感激。这是我见过的例外情况:

11:13:56,753 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) SQL Error: -170, SQLState: 42605
11:13:56,754 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) DB2 SQL Error: SQLCODE=-170, SQLSTATE=42605, SQLERRMC=COUNT, DRIVER=4.18.60
11:13:56,754 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) SQL Error: -516, SQLState: 26501
11:13:56,754 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) DB2 SQL Error: SQLCODE=-516, SQLSTATE=26501, SQLERRMC=null, DRIVER=4.18.60
11:13:56,754 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) SQL Error: -514, SQLState: 26501
11:13:56,754 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (batchProcessPool-1) DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURLN200C1, DRIVER=4.18.60
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
...

修改

感谢@ bowmore的建议,我修改了查询以使用exists()函数,它似乎正在工作!谢谢!

entityManager.createQuery(
    "select count(h) " +
    "from House h " +
    "where h.inspection_id between 1 and 10 " +
    "and exists (" +
        "select c.vin from Car c " +
        "where c.town = h.town " +
        "and c.state = h.state " +
        "and c.owner.id = h.owner.id " +
        "and c.vin between 12345 and 23456)",
Long.class).getSingleResult().intValue();

0 个答案:

没有答案