Suggested Pages

Tuesday, June 26, 2012

JPA: OneToMany Unidirectional Association

In this post we'll see an example of a unidirectional association OneToMany.

Object Point of View


Parent.java

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

 @OneToMany
 @JoinTable(name="Parent_Child", joinColumns=@JoinColumn(name="parentId"), inverseJoinColumns=@JoinColumn(name="childId"))
 private Set<Child> children;

 ...

}

Child.java

...

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



Database Point of View



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

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

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

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

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

As you can notice in the above snippet of code, we have three tables:
  • Child table;
  • Parent table;
  • Parent_Child: it has a primary key composed by parentId (the primary key of Parent table) and childId (the primary key of Child table).

No comments :

Post a Comment

Suggested Pages