Java – JPA: ignore field on save, but fetch on select


I am using Hibernate as my JPA provider, and I want one of the fields in an entity to be ignored when calling save(). However, I do have a matching column in the corresponding database table and I want my entity field to be populated with the database value when I fetch the entity. So, I want the field to be ignored when saving the entity, but not when fetching it.

If I use @Transient, the field is completely ignored, which is not what I want. Is there any way to do this?

Best Solution

From the excellent book Pro JPA 2 :

JPA defines options to set individual mappings to be read-only using the insertable and updatable elements of the @Column and @JoinColumn annotations. These two settings default to true but can be set to false if we want to ensure that the provider will not insert or update information in the table in response to changes in the entity instance. If the data in the mapped table already exists and we want to ensure that it will not be modified at runtime, then the insertable and updatable elements can be set to false, effectively preventing the provider from doing anything other than reading the entity from the database.

@Column(insertable = false, updatable = false)
private String readOnlyField;