Pregunta

I want to create a one-to-one relationship in Hibernate (XML mapping).

There are many examples showing how to do this. A popular example is a person with an address. The person table has got a foreign key to address. To be able to create a person record without an address you make the foreign key nullable.

That is not want I want. I want the opposite. In my database I have a table "Merchants" and a table "MerchantSettings". Every MerchantSettings record belongs to one Merchant and therefor has got a foreign key MerchantId. (In this way I can add merchant records without settings.)

In my code I have a class Merchant with a property Settings. What should the mapping look like?

(I do not want to have use 'component'. Table "MerchantSettings" has got it's own private key.)

Anybody knows how to do this?

[Update]

Because I do now want to use the same primary key as proposed by Karibasappa G C, I decided to add a foreign key to table "Merchants". I just make it nullable, so it is not required to have a MerchantSettings record (like the person/address examples).

It's not ideal, but I can work with it.

Thanks everybody.

Although it is not totally what I wanted, Marked Karibasappa G C's answer seems correct, and so I marked it as the accepted answer.

¿Fue útil?

Solución

As per your requirement, you need to make merchant as the owner of the relationship. merchant should have auto generated primary key.

and merchantsettings should have a primary key which is the foreign key from merchant table.

so if above understanding is correct here is the mapping for you

 merchant.hbm.xml

        <hibernate-mapping package="com.kb.model">

            <class name="Merchant">
                <id name="id" column="id">
                    <generator class="identity" />
                </id>

                <property name="name" column="NAME" />
         <one-to-one name="merchantsettings" cascade="all"/>
            </class>
        </hibernate-mapping>

    merchantsettings.xml

    <hibernate-mapping package="com.kb.model">
        <class name="merchantsettings">

            <id name="id" column="id">
                <generator class="foreign">
                <param name="property">merchant</param>
                </generator>
            </id>


     <one-to-one name="merchant" constrained="true"/>
        </class>
    </hibernate-mapping>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top