18

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?

1 Answer 1

38

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; 
Sign up to request clarification or add additional context in comments.

5 Comments

That help me, but how to get the value, if for example, this value is generated by default into my database?
In this case, the field is ignored and the value generated by database is not returned and stay to null
I have the same problem described by you. I have a field that is automatically generated by the database(default value) and it is not being returned by the save method, it just returns null. I have tried calling .flush() after saving but that did not work either. Did you get to the bottom of this?
UPDATE: In my case, I have a column modified_at and default value is current datetime. The only thing that worked for me was @UpdateTimestamp. I did not need to call .flush(). Neither @Generated or @GeneratedValue annotations worked, even after using .flush() the field would still come back as null after a .save().
Thank you, it helped. But also I had a java.sql.SQLSyntaxErrorException: Unknown column 'someobject0_.somereadonlyfield' in 'field list' when I tried to delete someobject by default JpaRepository method: someObjectsRepository.deleteById(someObjectId). Custom delete query helped me: @Query("delete from someobject where id = :someObjectId", nativeQuery = true)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.