Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate one to many using something other than a primary key

I have a class A that has a set of B's. However, these two objects are linked by fields that are NOT the primary key.

For B, I can use <key column>, but how do I specify that the join should be in A.secondary_column? Not A.table_primary_key_id ?

<class table="a">
    <id column="table_primary_key_id">
    </id>
    <property column="secondary_column" />

    <set table="B" lazy="false" >
        <key column="B_not_primary" />
        <one-to-many class="BClass" />
    </set>
</class>    
like image 276
Sergio Vera Avatar asked Aug 06 '09 19:08

Sergio Vera


People also ask

Does Hibernate work without primary key?

Hibernate requires that entity tables have primary keys.

Is primary key mandatory in Hibernate?

No, Hibernate will not work without primary key. Every table should have some unique key. The mathematical definition of a relation is a set of tuples.

How do you map a one to many relationship in Hibernate?

The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address.

How Hibernate define foreign key?

Foreign key refers to single column or group of columns in table that link data present in another table through its primary key. A Foreign key can't exist without its parent key but viceversa is not true. Want to be a Hibernate Master ?


1 Answers

Solved with

<set name="someSet" table="B" lazy="false">
    <key column="B_not_primary" property-ref="secondary_column" />
    <one-to-many class="BClass" />
</set>
like image 142
Sergio Vera Avatar answered Oct 22 '22 21:10

Sergio Vera