Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: mapping a value from another table column

Tags:

java

hibernate

I have a domain entity looks like this:

class Exch{
    private int id;
    private String val1;
    private String val2;

    @Column(name = "val1")        
    public String getVal1(){
        return val1;  
    }
    @Column(name = "val2")
    public String getVal2(){
        return val2;
    }
    @Column(name = "id")
    public int id(){
        return id;
    }
}

and table:

exch


Exch_ID| VAL1 | VAL2


100000 | AAA | BBB

200000 | CCC | DDD

now I have another table which looks like:

exch_extra


Exch_ID| VAL3 | VAL4


100000 | ZZZ| YYY

200000 | XXX| UUU

is there anyway I can map val3 in exch_extra table to Entity Exch without creating an extra Exch_extra entity?

so i can have:

class Exch{
    private int id;
    private String val1;
    private String val2;
    private String val3;


    @Column(name = "val1")        
    public String getVal1(){
        return val1;  
    }
    @Column(name = "val2")
    public String getVal2(){
        return val2;
    }
    @ do something here so i can have val3 from exch_extra table
    public String val3(){
        return val3
    }

    @Column(name = "id")
    public int id(){
        return id;
    }
 }
like image 217
user1409920 Avatar asked Apr 17 '13 16:04

user1409920


1 Answers

Hibernate has an @SecondaryTable annotation, which helps you map multiple table to an entity.

Just add secondary table annotation, join column (in secondary table) annotation.

Then map other columns like:

@Column(name="val3", table="table2")
private int val3;

where table2 is name of the other table.

like image 176
Amir Pashazadeh Avatar answered Oct 24 '22 15:10

Amir Pashazadeh