Here's an improvement proposal that would make Hibernate easier to use with immutable value-objects.
Let's say I have an immutable class like this:
Code:
class CreditCard {
private String number;
private String expMonth;
private String expYear;
public CreditCard(String number, String expMonth, String expYear) {
this.number = number;
this.expMonth = expMonth;
this.expYear = expYear;
}
public String getNumber() {
return number;
}
public String getExpMonth() {
return expMonth;
}
public String getExpYear() {
return expYear;
}
}
It has no setters, initialization is done using the constructor instead.
I propose that we teach Hibernate how to handle objects like this in a transparent way.
The mapping declaration could look something like this:
Code:
<class name="CreditCard" constructor-init="true">
<property name="number"/>
<property name="expMonth"/>
<property name="expYear"/>
</class>
constructor-init: false by default. If true, no setter methods are required for the properties. Instead a constructor is used to populate the object. The class must contain a constructor who's signature matches the given property types in the given order.
Rationale:
The use of immutable domain objects is a widely adopted design pattern, and currently the only way to make immutable objects persistent in Hibernate is to create wrapper classes or UserTypes or other hibernate-specific boilerplate (if I've done my homework correctly). Unnecessarily complex in most simple cases.
CreditCard, my case in point, is a very simple POJO. It just happens to be initialized through a constructor rather than through setter methods. I see no reason to have to jump through hoops to make that work in Hibernate.
This issue was also raised by jgro on Dec 5 - "Best Practice using UserTypes as components", but he gave up and resorted to UserTypes.
/Henrik Kniberg