Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Many to one Mapping with different Number of columns

Hi I have 2 tables as below

Table1:


    +-------------------+
    | ID  LOB col1 col2 |
    +-------------------+

Primary Key (ID and LOB)

Table2:


    +-----------------+
    | SK ID col3 col4 |
    +-----------------+

Primary Key (SK)

I need to give a many to one relation from table 2 to table1, since table1 has compositePrimaryKey(ID and LOB) but table2 does not have any column related to LOB. I am unable to provide the Mapping. Please help on this.

EDIT I have tried hibernate mapping for Table2:

<many-to-one name="class1Obj" class="com.acs.enterprise.common.Class1" 
            lazy="proxy" insert="false" update="false">
    <column name="ID" />
    <column name="LOB" />
</many-to-one>

The above is not working. While fetching a record it tries to fetch LOB code from table2 which is not at all exist in Table1

like image 833
Siva Avatar asked Jul 17 '15 13:07

Siva


1 Answers

Assuming table2.SK is a FK to table1.ID and there are no table1 entries having the same ID, you could write the mapping as follows:

@ManyToOne
@JoinColumn(name = "ID", insertable = false, updatable = false)
private Class1 class1Obj;

If there are more table1 rows with the same ID, the mapping will fail because a Child would then be matched to multiple Parents.

So, for a proper many-to-one association you need a FK to a Parent column that's unique.

like image 90
Vlad Mihalcea Avatar answered Oct 19 '22 13:10

Vlad Mihalcea