Suggested Pages

Saturday, June 30, 2012

JPA Mapping : Embedded Object

In JPA/Hibernate an embedded object resolve this question: how can you design in your application domain an object that is part of an entity bean? An embedded object is an object that it's not linked to a concrete table. An embedded object can't be directly persisted or queried because it's not an entity. It can only be persisted as part of another entity and so it doesn't need an id
Declaring an embeddable object is very simple.

Step-1: Create a class and annotate it with @Embeddable annotation


Address.java
...
@Embeddable
public class Address {
 
 @Column
 private String street;
 
 @Column
 private String cap;
 
...
}


Step-2: Use @Embedded annotation inside your entity bean


User.java
...

@Entity
public class User implements Serializable{

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int userId;

 @Column
 private String name;

 @Embedded
 private Address address;

...

}


Database Point of View

As i said before, you cannot persist or query an embedded object. Access to Address object requires access to User. If you try to persist Address object, you obtain the following error::
java.lang.IllegalArgumentException: Unknown entity: com.simonefolinojavablog.persistence.entity.Address.
If you use hibernate.hbm2ddl.auto property to automatically create tables in the DB, only one table is created.

   create table User (
        userId integer generated by default as identity (start with 1),
        cap varchar(255),
        street varchar(255),
        name varchar(255),
        primary key (userId)
    )
}

Override column names of an embedded object


In many cases an embedded object can be shared among entities but sometimes you need some variations to the field names of the embedded object.
Employee.java

...

@Entity
public class Employee {
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int employeeId;

 @Column
 private String name;

 @Embedded
   @AttributeOverrides({
     @AttributeOverride(name="street", column=@Column(name="jobstreet"))
   })
 private Address address;

   ...
 
}
JPA/Hibernate creates the table below. As you can see the column name street is converted into a column name called jobstreet. database point of view

  create table Employee (
        employeeId integer generated by default as identity (start with 1),
        cap varchar(255),
        jobstreet varchar(255),
        name varchar(255),
        primary key (employeeId)
    )
}

No comments :

Post a Comment

Suggested Pages