mitra4umohit wrote:
Hi
I am new to Hibernate and JPA.
I have one project requirement where I have to create mapping between 3 different tables.
For example
I have HD_TB table, ST_TB table and TC_TB table now
All 3 tables has many to many relationship with each other.
I want to create relation between all this 3 table in one table.
I mean for that table should have primary key of all 3 tables.
We are using Hibernate Annotation to create tables.
Please give some hint how I can achieve such mapping using Hibernate.
Regards,
Mohit Mehta
You could have a fourth entity that models the relation between these three entities. For exmaple, imagine you have TBL_A, TBL_B, and TBL_C then the following code should do it for you:
Code:
package test.model.data.jpa;
import javax.persistence.*;
import java.util.List;
import java.util.ArrayList;
/**
* @author Farzad Kohantorabi
* @created Jan 1, 2008
*/
@Entity
@Table(name = "TBL_A")
public class TableA
{
@Id @GeneratedValue
@Column(name = "Id")
public Long id;
@Column(name = "Name")
public String name;
@OneToMany(mappedBy = "a")
public List<RelationABC> relations = new ArrayList<RelationABC>(10);
}
Code:
package test.model.data.jpa;
import javax.persistence.*;
import java.util.List;
import java.util.ArrayList;
/**
* @author Farzad Kohantorabi
* @created Jan 1, 2008
*/
@Entity
@Table(name = "TBL_B")
public class TableB
{
@Id @GeneratedValue
@Column(name = "Id")
public Long id;
@Column(name = "Name")
public String name;
@OneToMany(mappedBy = "b")
public List<RelationABC> relations = new ArrayList<RelationABC>(10);
}
Code:
package test.model.data.jpa;
import javax.persistence.*;
import java.util.List;
import java.util.ArrayList;
/**
* @author Farzad Kohantorabi
* @created Jan 1, 2008
*/
@Entity
@Table(name = "TBL_C")
public class TableC
{
@Id @GeneratedValue
@Column(name = "Id")
public Long id;
@Column(name = "Name")
public String name;
@OneToMany(mappedBy = "c")
public List<RelationABC> relations = new ArrayList<RelationABC>(10);
}
and the relation class would be:
Code:
package test.model.data.jpa;
import javax.persistence.*;
/**
* @author Farzad Kohantorabi
* @created Jan 1, 2008
*/
@Entity
@Table(name = "REL_ABC")
public class RelationABC
{
@Id @GeneratedValue
@Column(name = "ID")
public Long id;
@ManyToOne
@JoinColumn(name = "A_ID")
private TableA a;
@ManyToOne
@JoinColumn(name = "B_ID")
private TableB b;
@ManyToOne
@JoinColumn(name = "C_ID")
private TableC c;
public void setA(TableA a)
{
this.a = a;
a.relations.add(this);
}
public void setB(TableB b)
{
this.b = b;
b.relations.add(this);
}
public void setC(TableC c)
{
this.c = c;
c.relations.add(this);
}
public TableA getA()
{
return a;
}
public TableB getB()
{
return b;
}
public TableC getC()
{
return c;
}
}
I can think of different configurations for cascading and everything but it really depends on your use cases. In any case, I don't believe you should use delete orphan option for the relations.
I hope this helps.
Farzad-