How to make Hibernate "realize" that the value of a column was set by the database
My Table in the database has a column that is automatically populated by the database itself.
This table is mapped as a class annotated with @ Entity, called EntidadeA
. The column that is autofilled is mapped to a property annotated with @Column, called prop1
.
When running EntityManager.persist(objeto)
, with the property prop1
= null
, hibernate runs a INSERT INTO tb... (coluna_prop1, ...) values (NULL, ...)
in the database.
At this point the database sets a YYY value in the column_prop1.
Question: How to make hibernate reread from the database, immediately after persist, the value of a column?
Note: I currently run EntityManager.refresh(objeto)
right after persist() --- it works, but this makes hibernate reread all database properties (ie. inefficient).
2 answers
Hibernate has a proprietary annotation to handle generated values, @Generated. It is little known, but it does exactly what you want (official documentation).
// Valores gerados tanto em inserts quanto updates
@Generated(GenerationTime.ALWAYS)
@Column(insertable = false, updatable = false)
private String propriedade1;
// Valores gerados apenas em inserts
@Generated(GenerationTime.INSERT)
@Column(insertable = false)
private String propriedade2;
JPA / Hibernate only maps every change that goes through it.
When making any change via database Hibernate is not aware that there has been this change.
In fact, I advise you to be very careful with this as it is a bad practice.
If you do not always refresh the entity another user may be left with the outdated version of the object which could cause data inconsistency.
Solutions would be:
- no let the database change the value, but put that logic in your project
- refresh the entity to fetch the correct value