【问题标题】:Hibernate query for entity based on whether related entity property is null?根据相关实体属性是否为空来对实体进行休眠查询?
【发布时间】:2009-05-21 23:07:54
【问题描述】:

我有以下映射:

<class name="Customer">
  <!-- actually one-to-one for all intents and purposes-->
  <many-to-one name="specialProperty" class="SpecialProperty" cascade="all" not-found="ignore" insert="false" update="false" column="id" unique="true"/>
</class

<class name="SpecialProperty" lazy="false">
        <id name="id" column="customer_id">
            <generator class="foreign">
                <param name="property">customer</param>
            </generator>
        <one-to-one name="customer" class="Customer" constrained="true"></one-to-one>
</class>

使用此映射,当 special_properties 表中没有特定客户的条目时,customer.specialProperty 为 null。(使用常规的一对一映射会导致 specialProperty 持有代理对象,所以我不能测试 null)所以在代码中我可以简单地做 customer.specialProperty == null 来查看客户是否有 SpecialProperty。

我正在尝试编写一个查询,该查询将返回所有具有非空 SpecialProperty 的客户,另一个查询将返回所有具有空 SpecialProperty 的客户。

我可以像这样获得具有非空 SpecialProperty 的客户:

from Customer customer inner join customer.specialProperty

但是,我无法获得没有 SpecialProperty 的客户(例如 customer.specialProperty == null)

我已经尝试了一些方法。基本上我想要的是类似

from Customer customer where customer.specialProperty is null

但这会生成用于测试 customer.id 无论出于何种原因是否为空的 sql。

建议?

【问题讨论】:

    标签: hibernate hql


    【解决方案1】:

    您的 specialProperty 定义中有 column="id"

    【讨论】:

    • 好的,这就解释了为什么它在生成的查询中检查 customer.id。但是,该 column="id" 是必需的,因为 SpecialProperty 实际上由表的主键表示。 (SpecialProperty的主键是对客户PK的引用)
    • 除了你应该有另一个属性来引用客户 ID
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多