HQL并检查对象是否为null或对象字段具有特定值

时间:2014-03-03 20:55:24

标签: java sql hibernate hql

执行以下查询时遇到问题:

from Customer c where c.connectedUserID = 1 and (c.connectedFinancialAnalyst is null or c.connectedFinancialAnalyst.completed = false)

对象c.connectedFinancialAnalyst可以为null。我需要的是找到没有金融分析师或财务分析师财产的客户具有特定价值。

编辑: 已完成的属性在postgres和java中是布尔值

Hibernate生成的输出

select
        customer0_.id as id1_0_,
        customer0_.birthDate as birthDat2_0_,
        customer0_.birthPlace as birthPla3_0_,
        customer0_.city as city4_0_,
        customer0_.email as email5_0_,
        customer0_.fatherName as fatherNa6_0_,
        customer0_.motherName as motherNa7_0_,
        customer0_.name as name8_0_,
        customer0_.pesel as pesel9_0_,
        customer0_.phoneNumber as phoneNu10_0_,
        customer0_.postalCode as postalC11_0_,
        customer0_.secondName as secondN12_0_,
        customer0_.sex as sex13_0_,
        customer0_.street as street14_0_,
        customer0_.surname as surname15_0_,
        customer0_.connectedFinancialAnalyst_id as connect17_0_,
        customer0_.connectedUserID as connect16_0_ 
    from
        Customer customer0_ cross 
    join
        FinancialAnalyst financiala1_ 
    where
        customer0_.connectedFinancialAnalyst_id=financiala1_.id 
        and customer0_.connectedUserID=1 
        and (
            customer0_.connectedFinancialAnalyst_id is null 
            or financiala1_.completed='false'
        )

2 个答案:

答案 0 :(得分:4)

您需要明确表示要进行左连接

from Customer c 
left join c.connectedFinancialAnalyst as analyst
where c.connectedUserID = 1 and (analyst.completed is null or analyst.completed = false)

答案 1 :(得分:0)

我将我的代码重写为Criteria,并且evrything工作得很好。我想tkat问题是左连接。当我使用标准时,我必须添加左外联连接,如:

Criteria c = session.createCriteria(Customer.class, "c").createAlias("c.connectedFinancialAnalyst", "analyst", JoinType.LEFT_OUTER_JOIN);

也许当我将查询中的左连接更改为左外联接时,一切都可能工作得很好^^。但是现在我的代码似乎更加用户友好了^^