Hibernate(n + 1)选择非PK连接

时间:2012-04-23 22:12:55

标签: java hibernate

(n + 1)选择我无法解决的问题。我正在加入非PK专栏。

我的架构

  

记录
   Record_Id(PK)
   Carrier_Number
  

  Audit_Details
  AuditId(PK)
  Carrier_Number

Records和Audit_Details之间存在一对多的关系。

我的records.hbm.xml

<set lazy="true" name="auditDetails" sort="unsorted"
        table="AUDIT_DETAILS" inverse="true">
        <key column="Carrier_Number" not-null="true" property-ref="carrierRefNumber"/>
        <one-to-many 
            class="com.package.AuditDtls" />
    </set>

我的auditDetails.hbm.xml

<many-to-one
        class="com.package.Records" fetch="join"
        name="Records" column="Carrier_Number" not-null="true" property-ref="carrierNumber" lazy="false"/>

这会产生类似

的查询
select
    this_.CARRIER_NUMBER as CARRIER1_2_2_,
    abc1_.CARRIER_NUMBER as CARRIER8_3_0_,
    otm4_.CARRIER_NUMBER as CARRIER1_2_1_,
from
    RECORDS this_ 
inner join
    AUDIT_DETAILS abc1_ 
        on this_.CARRIER_NUMBER=abc_.CARRIER_NUMBER 
left outer join
    RECORDS otm4_ 
        on abc1_.CARRIER_NUMBER=otmp4_.CARRIER_NUMBER 
where
    this_.LOAD_ID=? 

select
    auditde0_.CARRIER_NUMBER as CARRIER8_1_        
from
    AUDIT_DTLS auditde0_ 
where
    auditde0_.CARRIER_NUMBER=?

我尝试过更改为fetch =“select”,更改lazy =“false”和lazy =“no-proxy”但到目前为止还没有任何工作。我不确定这个问题是否是因为使用nonPK列连接两个表。将不胜感激任何建议。

1 个答案:

答案 0 :(得分:0)

问题在于我的标准而不是映射。通过在下面设置我的标准解决了这个问题。

createAlias("auditDetails", "ad", CriteriaSpecification.LEFT_JOIN);

此外,将Hibernate更新为3.3并移至注释并在下面设置解决了其他选择问题。

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "CARRIER_NUMBER")
public Records getRecord() {
    return record;
}