Reputation: 102
I have two classes Hotsheet and Invoice and one-to-one relation between them. I need to have a property in both classes which will link to each other. Here's my xml mapping of Invoice class.
<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. If Hotsheet could have few invoices I would map it this way:
<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.
Upvotes: 0
Views: 112
Reputation: 16354
You can follow this link for one-to-one mapping in Hibernate. So you hbm files may be as follows:
<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
.
BR.
Upvotes: 2