Wednesday, May 22, 2013

Hibernate - @AttributeOverrides

In hibernate-embeddable-and-embedded, we explained how to persist an object attribute. Let me take the Student class for example again, how we should do if we want to persist two Parent objects in Student, such as father and mother.

We can count on @AttributeOverrides
    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "name", column = @Column(name = "Father_Name")),
            @AttributeOverride(name = "phoneNo", column = @Column(name = "Father_PhoneNo")) })
    private Parent father;

    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "name", column = @Column(name = "Mother_Name")),
            @AttributeOverride(name = "phoneNo", column = @Column(name = "Mother_PhoneNo")) })
    private Parent mother;

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.setFather(father);
        student.setMother(mother);


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

See data in MySQL





No comments:

Post a Comment