Source Allies Logo

Sharing Our Passion for Technology

& Continuous Learning

<   Back to Blog

Hibernate Embeddable Objects

Hibernate Embeddable Objects are a really neat way to organize your data model.  Especially, if you have the same few columns in a number of different tables, that all pertain to the same thing. The example commonly used is Addresses.  You may have a number of tables that each have fields pertaining to address information and you don't want to have to do all the mappings for each entity again and again.  If the column names are the same across each table, you can just add an @Embeddable annotation.

Consider the following example:

@Embeddable
public class Address implements Serializable {
...
   private String lineOne;
   private String lineTwo;
   private String city;
....
   @Column(name = "LINEONE")
   public String getLineOne(){
      return this.lineOne;
   }
...
   @Column(name = "CITY")
   public String getCity(){
      return this.city;
   }
...

This creates address as an embeddable object. Then to actually embed it in your entity, you simply do something like the following:

@Entity
@Table(name= "Person")
public class Person implements Serializable{
...
   private Address address;
...
   @Embedded
   public getAddress() {
      return this.address;
   }
...
}

There is, however, one huge problem with this, especially when working with JSF. If all of the fields in the embeddable object are null for some reason or another, then the embeddable object never actually gets instantiated. There is a solution/hack that works around this - you modify the setter method to look something like the following:

@Entity
@Table(name= "Person")
public class Person implements Serializable{
...
   private Address address;
...
   public void setAddress(Address address){
      if (address != null){
         this.address = address;
      } else {
         this.address = new Address();
      }
   }
}

It's not particularly pretty, but it will dry your tears in a pinch. More on this solution can be found here.