简体   繁体   English

Hibernate相互一对一的关系

[英]Hibernate mutual one-to-one relation

I have two classes Hotsheet and Invoice and one-to-one relation between them. 我有两个类Hotsheet和Invoice以及它们之间的一对一关系。 I need to have a property in both classes which will link to each other. 我需要在两个类中都有一个属性,它们将相互链接。 Here's my xml mapping of Invoice class. 这是我的Invoice类的xml映射。

<hibernate-mapping>
<class name="...Invoice" table="invoices">
    <id name="invoiceId" column="INVOICE_ID"/>

    ...

    <many-to-one
            name="hotsheet"
            column="HOTSHEET">
    </many-to-one>
</class>
</hibernate-mapping>

Invoice has a foreign key that links to its Hotsheet and I also need a property in Hotsheet which will have its Invoice. Invoice有一个链接到其Hotsheet的外键,我还需要Hotsheet中的一个属性,该属性将具有其Invoice。 If Hotsheet could have few invoices I would map it this way: 如果Hotsheet可能只有很少的发票,我会这样映射它:

<hibernate-mapping>
<class name="package.Hotsheet" table="hotsheets">
    <id name="hotsheetId" column="HOTSHEET_ID"/>

    ...

    <bag name="invoices">
        <key column="HOTSHEET"/>
        <one-to-many class="...Invoice"/>
    </bag>
</class>
</hibernate-mapping>

But this was, Hotsheet will have a list which will always contain only one Invoice, while I need a property with Invoice, not list with one Invoice. 但就是这样,Hotsheet将有一个列表,它将始终只包含一个Invoice,而我需要一个带Invoice的属性,而不是带有一个Invoice的列表。

You can follow this link for one-to-one mapping in Hibernate. 您可以在Hibernate中按照此链接进行一对一映射。 So you hbm files may be as follows: 所以你的hbm文件可能如下:

<hibernate-mapping>
  <class name="...Invoice" table="invoices">
  <id name="invoiceId" column="INVOICE_ID"/>

  ...

  <many-to-one name="hotsheet" class="package.Hotsheet" column="INVOICE_HOTSHEET"  not-null="true" cascade="all" unique="true" />
  </class>
</hibernate-mapping>


<hibernate-mapping>
  <class name="package.Hotsheet" table="hotsheets">
  <id name="hotsheetId" column="HOTSHEET_ID"/>

  ...
  <one-to-one name="invoice" 
    property-ref="hotsheet"/>
</class>
</hibernate-mapping>

Note that to create the one-to-one relationship we use the many-to-one with constraint unique set to true for the column INVOICE_HOTSHEET . 请注意,要创建一对一关系,我们对INVOICE_HOTSHEET列使用多对一约束唯一设置为true。

BR. BR。

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

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