tags:

views:

328

answers:

4

Hi Gurus,

I am wondering how to write the model, hbm.xml for table

Company
-------
id(PK)
name
address
typeid(fk)

Type
----
id(PK)
type

class Company(){
int id;
String name;
String address;
Type type;
}

class Type(){
int id;
String type;
}

(with get/set methods)

How to write the hbm?

I am using the hibernate 3.x.

A: 
<class name="Company" table="company">
<id name="id" column="id">
    <generator class="foreign">
        <param name="property">type</param>
    </generator>
</id>
...
<one-to-one name="type"
    class="Type"
    constrained="true"/>
</class>

More details here.

Vincent Ramdhanie
In this case, the company gets the id from the type, which is strange, since there could be another one-to-one, or it could be null.
Stefan Steinegger
The question asked for one-to-one so thats why this was suggested.
Vincent Ramdhanie
+1  A: 

the given situation is a many-to-one situation, because 1 type can be assigned to multiple companies

Salandur
A: 

It's not obvious, but it's straight forward mapped with many-to-one.

<class name="Company" table="company">
<id name="id">
    <generator class="native">
        <param name="sequence">Company_SEQ</param>
    </generator>
</id>
...
<many-to-one 
    name="type"
    class="Type"
    constrained="true"/>
</class>
Stefan Steinegger
+1  A: 

Can you have multiple companies of the same type? Don't you really want a many to one relationship?

How about something like this (adapted from the Hibernate docs from here):

<class name="Company" table="company">
    <id name="id" column="id">
    ...
    </id>
    ....
    <many-to-one name="type" 
        class="Type"
        column="typeid" 
        not-null="true"/>
</class>

<class name="Type">
    <id name="id" column="id">
        ...
    </id>
</class>
A_M