Wednesday, May 22, 2013

Hibernate - @ElementCollection, @JoinTable and @JoinColumn

Another way to persist multiple Parent objects in Student is to use Collection. JPA persists all Parent objects in a separate table with student_id as its' foreign key.

Student code
    @ElementCollection
    @JoinTable(name = "STUDENT_PARENTS", joinColumns = @JoinColumn(name = "STUDENT_ID"))
    private Collection<parent> parentList = new ArrayList<parent>();

Test code
        Student student = new Student();
        student.setFirstName("James");
        student.setLastName("Bond");
        
        Parent father = new Parent();
        father.setName("Bruce Bond");
        father.setPhoneNo("8888 8888");
        
        Parent mother = new Parent();
        mother.setName("Jolie Bond");
        mother.setPhoneNo("6666 6666");
        
        student.getParentList().add(father);
        student.getParentList().add(mother);

Console output
Hibernate: alter table STUDENT_PARENTS drop foreign key FK3A2502C5B2F00DA3
Hibernate: drop table if exists STUDENT_INFO
Hibernate: drop table if exists STUDENT_PARENTS
Hibernate: create table STUDENT_INFO (STUDENT_ID integer not null auto_increment, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (STUDENT_ID))
Hibernate: create table STUDENT_PARENTS (STUDENT_ID integer not null, Parent_Name varchar(255), Parent_PhoneNo varchar(255))
Hibernate: alter table STUDENT_PARENTS add index FK3A2502C5B2F00DA3 (STUDENT_ID), add constraint FK3A2502C5B2F00DA3 foreign key (STUDENT_ID) references STUDENT_INFO (STUDENT_ID)
Hibernate: insert into STUDENT_INFO (FIRST_NAME, LAST_NAME) values (?, ?)
Hibernate: insert into STUDENT_PARENTS (STUDENT_ID, Parent_Name, Parent_PhoneNo) values (?, ?, ?)
Hibernate: insert into STUDENT_PARENTS (STUDENT_ID, Parent_Name, Parent_PhoneNo) values (?, ?, ?)

In database









Please notice that table STUDENT_PARENTS has no primary key.

No comments:

Post a Comment