Suggested Pages

Friday, September 28, 2012

JPA Bidirectional Association

In this post we'll see an example of a bidirectional OneToMany-ManyToOne relationship in JPA.
A common example of OneToMany-ManyToOne relationship is Parent-Child relationship.

Object Point of View



Child.java

...

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

...

}

Parent.java

...
@Entity
public class Parent {
 
 @Id
 private int parentId;
 
 @Column
 private String name;

 @OneToMany(mappedBy="parent")
 private List children;
        
 ...
}


Database Point of View

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

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

alter table Child 
        add constraint FK3E104FC9E7EF479 
        foreign key (parent_parentId) 
        references Parent


As you can see, if you don't tell JPA to use a Join Table explicitly only two tables are created: the Child table that has a foreign key to Parent table .

No comments :

Post a Comment

Suggested Pages