hibernate HQL检查OneToOne关系中的NULL

kqqjbcuj  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(209)

下面是我的两个实体:

@Entity
@Table(name = "aog_reference")
public class AogReference
{
    @OneToOne(fetch = FetchType.LAZY, mappedBy="aogReference", cascade=CascadeType.ALL, optional=true)
    private Pack pack;

}

@Entity
@Table(name = "pack")
public class Pack
{

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="aog_reference")   
    private AogReference aogReference;

}

我可以使用Hibernate读写这两个实体,并且AogReference的***pack***属性被正确填充。
但是,我正在尝试运行一个HQL查询,该查询包含AogReference实体,而这些实体没有包引用它们。
在读了大量关于这方面的材料后,我希望这能起作用:

SELECT e FROM AogReference AS e left join e.pack  WHERE  (e.pack IS NULL)

但是我得到0行返回,即使我知道有AogReference实体没有任何来自Pack实体的引用。
我看过上面的hql生成的SQL,它看起来像这样:

select
        aogreferen0_.id as id1_0_,
        aogreferen0_.active as active2_0_,
        aogreferen0_.created as created3_0_,
        aogreferen0_.modified as modified4_0_,
        aogreferen0_.version as version5_0_,
        aogreferen0_.aog_delivery_number as aog_deli6_0_,
        aogreferen0_.aog_destination as aog_dest7_0_,
        aogreferen0_.aog_notes as aog_note8_0_,
        aogreferen0_.foc_notification_time as foc_noti9_0_,
        aogreferen0_.is_collection_today as is_coll10_0_,
        aogreferen0_.is_used as is_used11_0_,
        aogreferen0_.work_stream as work_st12_0_ 
    from
        aog_reference aogreferen0_ 
    left outer join
        pack pack1_ 
            on aogreferen0_.id=pack1_.aog_reference 
    where
        aogreferen0_.id is null

或简化:

select * 
 from 
   aog_reference a 
 left outer join 
    pack p on a.id = p.aog_reference 
 where a.id is null

现在请注意这个巨大的错误:

where a.id is null

Hibernate完全搞错了,生成的sql应该是这样的:

select
        aogreferen0_.id as id1_0_,
        aogreferen0_.active as active2_0_,
        aogreferen0_.created as created3_0_,
        aogreferen0_.modified as modified4_0_,
        aogreferen0_.version as version5_0_,
        aogreferen0_.aog_delivery_number as aog_deli6_0_,
        aogreferen0_.aog_destination as aog_dest7_0_,
        aogreferen0_.aog_notes as aog_note8_0_,
        aogreferen0_.foc_notification_time as foc_noti9_0_,
        aogreferen0_.is_collection_today as is_coll10_0_,
        aogreferen0_.is_used as is_used11_0_,
        aogreferen0_.work_stream as work_st12_0_ 
    from
        aog_reference aogreferen0_ 
    left outer join
        pack pack1_ 
            on aogreferen0_.id=pack1_.aog_reference 
    where
        pack1_.id is null

请注意,最后一行现在是:

where pack1_.id is null

Hibernate生成的sql在应该检查Pack的id时却在检查AogReference上的id。
当我在我的数据库中启动它时,纠正后的sql工作正常。
在我看来,这就像是Hibernate中的一个巨大的bug,它根本没有生成正确的SQL。
任何意见(明智的)感激地收到。
谢谢你,
艾德
更新:看起来这是一个hibernate bug,它从2010年就已经存在了。

ctehm74n

ctehm74n1#

正如您已经提到的,这似乎是一个已知的hibernate bug
对于任何遇到这个问题的人来说,一个解决方法是使用“Exists”:

SELECT e FROM AogReference e WHERE NOT EXISTS (SELECT p FROM Pack p WHERE p.aogReference = e)

相关问题