'JPA equivalent of Hibernate's @Generated(GenerationTime.ALWAYS)
When certain non key fields of a entity are generated in the database (for instance, by triggers) a call to persist
will not bring back values that the database has just generated. In practice this means that you may need to refresh
an entity after persist
or merge
(and when level 2 cache is enabled you may even need to evict
the entity).
Hibernate have a custom annotation @Generated
which handles Generated Properties.
// Refresh property 1 on insert and update
@Generated(GenerationTime.ALWAYS)
@Column(insertable = false, updatable = false)
private String property1;
// Refresh property 2 on insert
@Generated(GenerationTime.INSERT)
@Column(insertable = false)
private String property2;
JPA @GeneratedValue
only works with primary key properties.
So, my question is if there is a replacement for @Generated
on JPA API (maybe on 2.1)? And if there isn't one, what is the best practice to handle non key database generated fields?
Solution 1:[1]
I read the specs from the beginning until the end and it is not such thing, nothing comparable with @Generated, sorry , and as you said.
The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.
What you could do is use Event Listener @PrePersist and @PreUpdate to set some properties by default or generated by utility classes before em persist the object , try that approach it comes to my mind to something similiar.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Koitoer |