2

我正在使用 Java 1.6、Hibernate 3.1、MySQL 5.5、XML 映射。我有两个表,partner 和 partner_http_account。我将向您展示相关领域。

伙伴:

partnerid dec(22,0) [primary key]

partner_http_account:

partnerhttpacctid dec(22,0) [primary key]
partnerid dec(22,0) [foreign key]

这是 XML 映射:

<class name="com.rc.model.partner.Partner" table="partner" mutable="true">
    <id name="partnerId" type="int">
        <column name="partnerid" scale="10" precision="0" not-null="true" unique="true" sql-type="int unsigned"/>
        <generator class="com.rc.model.jdbc.sequence.MexpIdentifierGenerator">
            <param name="sequence">seq_partnerid</param>
            <param name="idDataType">int</param>
        </generator>
    </id>
    ...
    <one-to-one name="partnerHTTPAccount" class="com.rc.model.partner.PartnerHTTPAccount" lazy="false"
                 foreign-key="partnerid" cascade="all"/>
</class>

<class name="com.rc.model.partner.PartnerHTTPAccount" table="partner_http_account">
    <id name="partnerHttpAcctId" type="int">
        <column name="partnerhttpacctid" scale="10" precision="0" not-null="true" unique="true" sql-type="int unsigned"/>
        <generator class="com.rc.model.jdbc.sequence.MexpIdentifierGenerator">
            <param name="sequence">seq_partnerhttpacctid</param>
            <param name="idDataType">int</param>
        </generator>
    </id>

    <many-to-one name="partner" class="com.rc.model.partner.Partner" column="partnerid"
                 foreign-key="partnerid" cascade="none"/>
</class>

这是我的Java代码:

public List<Partner> getPartnersByDomainStartsWith(String domainStartsWith) {

    Query hQuery = sessionManager.getSession().createQuery("from Partner p " +
            "left outer join fetch p.partnerHTTPAccount " +
            "where p.domain like :domainStartsWith||'%'");

    hQuery.setString("domainStartsWith", domainStartsWith);

    return hQuery.list();
}

这是 Hibernate 生成的:

select partner0_.partnerid as partnerid0_,
partnerhtt1_.partnerhttpacctid as partnerh1_1_,
...
partnerhtt1_.partnerid as partnerid104_1_,
...
from partner partner0_
left outer join partner_http_account partnerhtt1_ on partner0_.partnerid=partnerhtt1_.partnerhttpacctid 
where partner0_.domain like concat(?, '%')

我的问题是这两个表生成的 sql 查询加入了错误的字段。它应该加入partner0.partnerid=partnerhtt1.partnerid。真的很感激一些见解。谢谢。

4

1 回答 1

0

这在Hibernate 文档中得到了很好的描述:

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <many-to-one name="address" 
        column="addressId" 
        unique="true"
        not-null="true"/>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
   <one-to-one name="person" 
        property-ref="address"/>
</class>

请注意如何使用 property-ref,以指示一对一是地址属性映射的关联的反面。

于 2012-06-11T19:32:12.097 回答