Saturday, October 18, 2014

Working with immutable objects and hibernate

To support a rich domain model, it's often a good idea to make domain objects immutable. Hibernate if however not happy about this. It works best with objects who only has a default constructor and getter and setters for all fields. 
To make hibernate work with immutable objects, declare a default constructor with at least package level visibility. 
If mapping-annotations is placed on fields the access type will be AccessType.FIELD. If placed on methods the access type will be AccessType.PROPERTY. Field type access is needed by hibernate for handling final attributes.
 
 @Entity  
 @Table(name = "person")  
 public class Person {  
   
      @Id  
      @Column(columnDefinition = "BINARY(16)", length = 16)  
      private final UUID id;  
      private final Date creationDate;  
      private final String firstname;  
      private final String lastname;  
   
      // Hibernate needs this or it will fail with an InstantiationException  
      private Person() {  
           this.id = UUID.randomUUID();  
           this.creationDate = new Date();  
           this.firstname = null;  
           this.lastname = null;  
      }  
   
      public Person(String firstname, String lastname) {  
           this.id = UUID.randomUUID();  
           this.creationDate = new Date();  
           this.firstname = firstname;  
           this.lastname = lastname;  
      }  
 }  

If you are using XML mappings, this can also be done by setting:

<hibernate-mapping default-access="field" package="com.blogspot.jpdevelopment.immutable.hibernate.core.domain">

A full example is available here.

No comments:

Post a Comment