簡體   English   中英

如何將 INNER JOIN 和 LEFT JOIN 與 JPQL 和 HQL 結合使用

[英]How to combine INNER JOIN and LEFT JOIN with JPQL and HQL

我正在嘗試實現 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

如果在 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'
 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM