Sunday, March 18, 2012

Hibernate 4.1 new features loading per @NaturalId

What features come along with the new Hibernate 4 Release?
In Release 4, to be correct 4.1-Release, one can load entities with naturalIds.

What are naturalIds?
NaturalIds are keys with professional uniqueness, which can be used in certain queries or loading situations. It is recommendate that technical keys are used, but if those entities have attributes with professional uniqueness, those attributs can be assigned hibernate annotations
@NaturalId. Those properties must be unique, because
an unique constraint will be created on that column in the database.


Why should I bother about @NaturalId - annotations anyway?
Assumpted that there is an entity taxpayer. It certainly has a property named taxnumber.
The taxnumber should be unique.
So this property is a candidate for a definition of an naturalId.

public class Taxpayer {
  @Id
  @GeneratedValue
   private Long id;
   private String firstname;
   ....
   @NaturalId
   private String taxnumber;
   ...
}

Now you have an advantage, which could be used already in older hibernate versions:
You can make use of those naturalIds in queries:
Session s = ...
Criteria crit = s.createCritera(Taxpayer.class);
Taxpayer t = (Taxpayer) crit.add(Restrictions.naturalId("taxnumber").set("89089083AST8908").uniqueResult();

New 4.1 feature:
With 4.1 you can define @NaturalId in the entity and use it on the session object, that means you
can load an entity with help of byNaturalId()!

Session s = ...
TayPayer t = (TaxPayer) s.bySessionId(Taxpayer.class).using("taxnumber", "89089083AST8908");


Is there an disadvantage?
Unfortunately, the @NaturalId is a hibernate specific feature.
So you can't express / use @NaturalIds in JPA.
It seems, that @NaturalId will not be included in the upcoming JPA 2.1 standard.
See: Early Draft JPA 2.1

1 comment: