How to make Hibernate "notice" that the value of a column has been set by the database

3

My table in the database has a column that is populated automatically by the database itself.

This table is mapped as a class annotated with @Entity, called EntidadeA . The column that is populated automatically is mapped to a property annotated with @column, called prop1 .

When running EntityManager.persist(objeto) , with the prop1 property null property, hibernate executes a INSERT INTO tb... (coluna_prop1, ...) values (NULL, ...) in the database. At this point the database points to a YYY value in column_prop1.

Question: How to make the hibernate reler of the database immediately after the persist, the value of a column ?

Note: I currently run EntityManager.refresh(objeto) shortly after persist () --- it works, but this causes hibernate to rerun all database properties (ie inefficient). >     

asked by anonymous 17.02.2014 / 19:15

2 answers

3

Hibernate has a proprietary annotation to handle generated values, @ Generated . It is little known, but 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;
    
17.02.2014 / 19:42
2

JPA / Hibernate only maps every change that passes through it.

When making any changes via the database, Hibernate is not aware that this change occurred.

In fact, I advise you to be very careful about this as it is 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:

  • Do not let the database change the value, but put this logic in your project
  • Refresh the entity to fetch the correct value
  • 17.02.2014 / 19:28