Suggested Pages

Wednesday, June 27, 2012

JPA: ManyToOne unidirectional association with JoinTable

In this post we'll see an example of a unidirectional ManyToOne with JoinTable relationship in JPA.

Object Point of View


Parent.java
 ...

@Entity
public class Parent {

 @Id
 private int parentId;

 @Column
 private String name;

 ...

}

Child.java
     ...

@Entity
public class Child {
 
 @Id
 private int childId;
 
 @Column
 private String name;

 @ManyToOne
 @JoinTable(name="Parent_Child", joinColumns=@JoinColumn(name="childId"), inverseJoinColumns=@JoinColumn(name="parentId"))
 private Parent parent;
 
 ... 

}


Database Point of View


[

create table Child (
        childId integer not null,
        name varchar(255),
        primary key (childId)
)

create table Parent (
        parentId integer not null,
        name varchar(255),
        primary key (parentId)
)

create table Parent_Child (
        parentId integer,
        childId integer not null,
        primary key (childId)
)

alter table Parent_Child 
        add constraint FK5AF11D47C916AC84 
        foreign key (parentId) 
        references Parent

alter table Parent_Child 
        add constraint FK5AF11D47ABE0291E 
        foreign key (childId) 
        references Child

As you can see in the above snippet of code Parent_Child is a table that has two foreign keys: the former with Parent table and the latter with Child table.
The Parent_Child table has also childId as primary key because a child cannot have different parents.

No comments :

Post a Comment

Suggested Pages