Search This Blog

Monday 5 August 2013

Excluding a property from the ORM framework

If we have a property that does not map to any column in the table, we simply do not specify that property in our hbm files. But with JPA annotations it is a little different. A class if marked with an Entity annotation, all its properties are considered persistent by default. So how do we exclude a property ?
One option is to mark the field transient.
@Entity
@Table
public class Pojo {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private long id;
 @Column
 private String name;
 @Column
 private transient int number;
//setter getters
}
If I were to run this code with the hbm2ddl.auto option set to create, it would totally ignore the number property. The SQL generated would be :
7219 [main] DEBUG org.hibernate.tool.hbm2ddl.SchemaExport  - 
    create table firstOne.Pojo (
        id  bigserial not null,
        name varchar(255),
        primary key (id)
    )
The transient property would ensure that the column is ignored. Even the Column annotation that I left on the property did not see it included in the SQL.
The problem with the above approach is that it affects the serialization behaviour of the class  - an unwanted side effect. If we were to use this class in any serializable environment then the number property will not be preserved.
JPA provides an alternative solution - the javax.persistence.Transientannotation.
 @Transient
 private int number;
With this in place we can ensure that this column is not visible to the JPA provider.

No comments:

Post a Comment