Hibernate 使用或休眠查询不显示结果
我们试图通过HQL执行以下查询,但是我们被卡住了,这个查询没有显示任何结果Hibernate 使用或休眠查询不显示结果,hibernate,hql,Hibernate,Hql,我们试图通过HQL执行以下查询,但是我们被卡住了,这个查询没有显示任何结果 select s from Serie s where (s.arrivalSerie is not null and s.arrivalSerie.company.isEnable=1) or (s.departureSerie is not null and s.departureSerie.company.isEnable=1) 我们将通过以下方式抛出此查询: Query query = em.createQue
select s from Serie s where
(s.arrivalSerie is not null and s.arrivalSerie.company.isEnable=1)
or (s.departureSerie is not null and s.departureSerie.company.isEnable=1)
我们将通过以下方式抛出此查询:
Query query = em.createQuery("previous query");
query.setFirstResult(initialElement);
在测试此查询时,我们发现此查询的任何部分(“或”)都可以使用结果执行。但是当整个查询执行时,我们得到0个元素集合
有什么想法吗
更新:
可以理解的翻译查询如下:
select
s.*
from
serie s,
arrivalSerie a,
company ca,
departureSerie d,
company cd
where
s.idArrivalSerie=a.idArrivalSerie
and a.CompanyCode=ca.CompanyCode
and s.idDepartureSerie=d.idDepartureSerie
and d.CompanyCode=cd.CompanyCode
and (
(
s.idArrivalSerie is not null
)
and ca.isEnable=1
or (
s.idDepartureSerie is not null
)
and cd.isEnable=1
) limit 0,10;
当然,这并没有显示MySql客户端上的结果
s.arrivalSerie.company
在Serie
和arivalserie
之间创建一个内部联接,并在arivalserie
和公司
之间创建另一个内部联接。内部联接将过滤掉所有具有空到达序列的序列,这显然不是您想要的。因此,您需要使用左连接:
select s from Serie s
left join s.arrivalSerie arrivalSerie
left join arrivalSerie.company arrivalCompany
left join s.departureSerie departureSerie
left join departureSerie.company departureCompany
where arrivalCompany.isEnable = 1 or departureCompany.isEnable = 1
您可以检查此hql生成的sql吗?您可以通过在hibernate配置中将show sql属性设置为true来进行调试,控制台将打印生成的sql查询,您可以对数据库运行它并找出答案。变量
initialElement
包含什么?如果您想要第一个元素,您应该将其设置为0。谢谢,我们终于自己找到了相同的解决方案。无论如何,我们非常感谢您的解释(老实说,我们不知道初始查询到底发生了什么)。您应该在开发过程中始终打开SQL日志记录,以查看Hibernate如何将HQL转换为SQL,并找到这些问题的原因。