Wednesday, May 22, 2013

Hibernate - @Embeddable, @Embedded and @EmbeddedId

In last post, all the attributes we persisted for Student object were quite simple, like int, String and Date. How we persist object attribute for Student class like Parent? Suppose Parent has two fields: name and phone number.

JPA provides @Embeddable and @Embeded to help us achieve this goal.

Create a new Parent class
package com.mqin.hibernate.demo;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Parent {
    @Column(name="Parent_Name")
    private String name;
    
    @Column(name="Parent_PhoneNo")
    private String phoneNo;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }
    
}



Student code
@Entity
@Table(name = "STUDENT_INFO")
public class Student {

    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    private int ID;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;
    
    @Embedded
    private Parent parent;

Test code
        Student student = new Student();
        student.setFirstName("James");
        student.setLastName("Bond");
        
        Parent parent = new Parent();
        parent.setName("Bruce Bond");
        parent.setPhoneNo("8888 8888");
        
        student.setParent(parent);

Console output
Hibernate: drop table if exists STUDENT_INFO
Hibernate: create table STUDENT_INFO (STUDENT_ID integer not null auto_increment, FIRST_NAME varchar(255), LAST_NAME varchar(255), Parent_Name varchar(255), Parent_PhoneNo varchar(255), primary key (STUDENT_ID))
Hibernate: insert into STUDENT_INFO (FIRST_NAME, LAST_NAME, Parent_Name, Parent_PhoneNo) values (?, ?, ?, ?)

See what's in database






Note: Use @EmbeddedId if you would like some object to be your primary key.

No comments:

Post a Comment