How to make Hibernate "realize" that the value of a column was set by the database

Asked

Viewed 599 times

3

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

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

When executing EntityManager.persist(objeto), with the property prop1 = null, Hibernate performs a INSERT INTO tb... (coluna_prop1, ...) values (NULL, ...) in the database. At that moment the database arrow a YYY value in the column_prop1.

Question: How to make Hibernate reread from the database, immediately after the persist, the value of a column?

Note: Currently running EntityManager.refresh(objeto) right after persist() --- it works, but this makes Hibernate re-read all the database properties (ie. inefficient).

2 answers

3


Hibernate has a proprietary annotation to handle generated values, @Generated. She’s little known, but she 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;
  • thiagoinu, here’s how to control the "item 1" of the other answer

  • 2

    Spark, actually this option does not cause the application to change the database. It is the counterpart of item 2, doing the automatic "refresh" of the marked columns for pre-configured simple types (think about getGeneratedKeys() of the JDBC).

2

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

When making any change via database Hibernate is not aware that there has been such change.

Actually, I would advise you to be very careful with that because it’s bad practice.

If you don’t always give the refresh in the entity another user may get the outdated version of the object which could cause data inconsistency.

Solutions would be:

  1. Don’t let the database change the value, but put this logic into your project
  2. Refresh the entity to get the correct value
  • +1 in item 1. Make the logic in a callback of save to record the data correctly and in a system of multiple simultaneous accesses do not leave models cached, always search from the base.

  • Item 2 then, because I do not control item 1. Refresh() immediately after Persist() is ugly, because I just created the object, but since it is the only solution...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.