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?
To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.
When persisting Java objects into database records using an Object-Relational Mapping (ORM) framework, we often want to ignore certain fields. If the framework is compliant with the Java Persistence API (JPA), we can add the @Transient annotation to these fields.
@Transient annotation is used to ignore a field to not persist in database in JPA, where as transient key word used to ignore a field from serialization. The field annotated with @Transient still can be serialized, but the field declared with transient keyword not to be persisted and not to be serialized.
The @Transient annotation tells the JPA provider to not persist any (non- transient ) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient property and still serialize it.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With