简体   繁体   English

在外键上一对一休眠

[英]hibernate one to one on foreign key

I have a main table that is D1 which has a unique id of d1Id. 我有一个主表是D1,它的唯一ID为d1Id。 d1Id uniquely identifies the D1 records and is also a primary key on the table. d1Id唯一标识D1记录,并且还是表上的主键。 I have table 2 which is D2 which has a d2seq as a primary key but D2 also has d1Id which is unique which has a foreign key constraint (I think) on D1. 我有表2,它是D2,它具有d2seq作为主键,但是D2也具有d1Id,这是唯一的,它对D1具有外键约束(我认为)。 But I know for sure it's unique and the id's are the same. 但我可以肯定它是唯一的,并且ID是相同的。 I am trying to retrieve d2 values when i make the D1 call using hibernate and i'm unable to get the right hbm for it as i'm getting compile time errors. 我尝试使用休眠方式进行D1调用时检索d2值,但由于编译时错误而无法为其获取正确的hbm。

The bottom line of the issue is, I need to establish a one to one relationship between 2 tables where in the second table, the id which joins is not the primary key of the table. 问题的底线是,我需要在2个表之间建立一对一关系,其中在第二个表中,联接的id不是表的主键。 All the examples i've seen searching google have the case where the ID on the second table is also the primary key of the second table. 我在搜索google时看到的所有示例都有第二个表上的ID也是第二个表的主键的情况。 Let me show you the HBM file I have right now. 让我告诉您我现在拥有的HBM文件。

<hibernate-mapping default-lazy="true"
package="com.xxx.xx.customer.dto">
<class name="D1" table="D1" dynamic-update="true">
    <id name="dString" column="DID" type="java.lang.String"
        unsaved-value="null" length="9">
        <generator class="assigned"/>
    </id>
...

<one-to-one name="d2" class="com.xxx.xx.customer.dto.D2" >
        <!-- column name="d1Id" /-->
    </one-to-one>

In my second hbm for D2, i'm stuck here 在D2的第二个HBM中,我被困在这里

<hibernate-mapping default-lazy="true" package="com.xxx.xx.customer.dto">
<class name="D2" table="D2" dynamic-update="true">
    <id name="id" column="D2ID" type="integer">
        <generator class="native">
            <param name="sequence">D2SEQ</param>
        </generator>
    </id>

<id name="d1id" column="D1ID" type="java.lang.String"
        unsaved-value="null" length="9">
        <generator class="assigned"/>
    </id>

I obviously can't use the second id field for d1id here because 1> it's not a primary key and 2> i've already used it before. 我显然不能在这里使用第二个id字段作为d1id,因为1>它不是主键,并且2>我以前已经使用过它。 So how should my HBM files be for this operation? 那么我的HBM文件应如何用于此操作?

Also once I have my HBMs in place, I would like to get D2 information while i query D1 through the DTOs. 同样,当我有了HBM时,我想通过DTO查询D1时获得D2信息。 How can I do that? 我怎样才能做到这一点?

Why can't you use @ManyToOne relationship? 为什么不能使用@ManyToOne关系? Often it provides more flexibility than @OneToOne 通常,它比@OneToOne提供更大的灵活性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM