【问题标题】:How to combine INNER JOIN and LEFT JOIN with JPQL and HQL如何将 INNER JOIN 和 LEFT JOIN 与 JPQL 和 HQL 结合起来
【发布时间】:2015-05-19 10:29:54
【问题描述】:

我正在尝试实现 HQL 查询。我已经能够在 SQL 中实现它——我对它有点熟悉。我一直挂断的是INNER JOINS。

类是这样实现的...

class Item

class Component extends Item
    private Item parentItem;

class Assembly extends Item 

到目前为止,这就是我的 HQL...

SELECT
item.blah,
comp.blah,
assembly.blah
FROM
Component comp
LEFT OUTER JOIN comp.parentItem item,
Assembly assembly
WHERE 
item.parentItem = assembly

这行得通 - 除了我需要最后三行是一个 LEFT OUTER JOIN 而不是互斥条件。我尝试以多种方式实现这一点 - 但我一直遇到映射问题。

<hibernate-mapping>
    <class lazy="false" name="com.kcp.common.domain.inventory.Item"
   table="W_INV_INV_ITEM" where="deleted=0">

       <joined-subclass lazy="false" name="com.kcp.common.domain.inventory.Component" table="W_INV_INV_COMPONENT">
         <key>
           <column name="ID">
               <comment>Primary and foreign key to W_INV_INV_ITEM.</comment>
            </column>
         </key>
         <many-to-one cascade="all" class="com.kcp.common.domain.inventory.Item" name="parentItem" outer-join="true">
              <column name="PARENT_ITEM_ID">
                <comment>Foreign key identifying the item to which this component is assembled.</comment>
              </column>
         </many-to-one>
       </joined-subclass>

        <joined-subclass lazy="false" name="com.kcp.common.domain.inventory.Assembly" table="W_INV_INV_MAJOR_ASSEMBLY">   
          <key>
            <column name="ID">
              <comment>Primary and foreign key to W_INV_INV_ITEM.</comment>
            </column>
          </key>
    </class>
 </hibernate-mapping>

另外 - 我让它像这样在 SQL 中工作......

FROM
DBO.W_INV_INV_ITEM item
INNER JOIN DBO.W_INV_INV_COMPONENT comp ON item.id = comp.id
LEFT OUTER JOIN DBO.W_INV_INV_ITEM parentInv ON comp.PARENT_ITEM_ID = parentInv.id
LEFT OUTER JOIN DBO.W_INV_INV_MAJOR_ASSEMBLY parentMA ON comp.PARENT_ITEM_ID = parentMA.id

【问题讨论】:

    标签: java sql hibernate hql hibernate-mapping


    【解决方案1】:

    如果您在 WHERE 子句中包含 LEFT JOIN 条件,它将充当 INNER JOIN。

    如果item 是可选的,那么item.parentItem 也必须是可选的,因此您需要将其包含在LEFT JOIN 中。

    试试这样的:

    SELECT
        i.blah,
        c.blah
    FROM Component c
    LEFT JOIN c.parentItem i
    LEFT JOIN i.parentItem p
    WHERE 
        p is null or p.class = 'Assembly'
     
    

    【讨论】:

    • 越来越近 - 只要添加 LEFT JOIN i.parentItem p 行,我仍然会收到 SQL.GrammerException 错误。我知道它将 parentItem 识别为成员变量 - 但它仍然抛出 GrammerException 错误。
    • 您需要发布您的实体。
    • 我添加了 hibernate-mapping 的总结版本。这行得通吗?
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 2017-12-07
    • 2018-08-02
    • 2016-12-29
    • 2012-08-17
    • 2014-03-11
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多