Search This Blog

Saturday 14 September 2013

Hibernate's custom annotations

In the previous few posts we saw how JPA provides us with an annotation driven approach to configure our entities. As with all standard APIs, when vendors implemented JPA, they found that the annotations did not cover every nifty trick provided by the implementations.
Accordingly the Hibernate team (which is one such provider) decided to provide custom annotations - for their custom functionalities. I have covered most of these functionalities in detail when discussing the hbm approach. I decided to try out their equivalent annotations.

Using derived properties :
We saw earlier how Hibernate gives us the ability to create derived properties. For the annotation based approach we have
public class Pojo {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private long id;
 @Column
 private String name;
 @org.hibernate.annotations.Formula(value = "EXTRACT(YEAR FROM age( dateOfBirth::date))")
 private long age;
 @Temporal(value= TemporalType.DATE)
 private Date dateOfBirth;
//..setter getters
}
The formula used determines the age of the pojo from the date of birth. The SQL query fired is as below:
select
        pojo0_.id as id0_0_,
        pojo0_.dateOfBirth as dateOfBi2_0_0_,
        pojo0_.name as name0_0_,
        EXTRACT(YEAR 
    FROM
        age( pojo0_.dateOfBirth::date)) as formula0_0_ 
    from
        firstOne.Pojo pojo0_ 
    where
        pojo0_.id= ?

Database Generated column values:
We saw how there may be cases when the value is generated by the database for e.g. a trigger. In such cases we need to ensure that Hibernate updates the POJO's value after it performs a save or an update operation.
@org.hibernate.annotations.Generated(GenerationTime.ALWAYS)
private int markUnverified;
This will ensure that Hibernate will update the POJO after insert and update. Other values are GenerationTime.INSERT and GenerationTime.NEVER.

Marking an Entity as Read Only :
We have seen the advantages in indicating to Hibernate that certain data will never be updated via code. For example master data. For annotation based mapping we have
@Entity
@Table(schema = "firstOne")
@org.hibernate.annotations.Immutable
public class Pojo {
This indicates that the Entity is immutable and not to be updated by JPA.

No comments:

Post a Comment