Reputation: 484
Say I have a persistent property A
in an entity, and 2 transient fields T1
, T2
. When the entity is persisted, I need to calculate A
based on T1
, T2
(suppose this is a legacy database which can not be altered).
@Entity
Class MyEntity {
@Column(name="persistantA")
Integer A;
@Transient
Integer T1;
@Transient
Integer T2;
@PrePersist
void prePersist() {
A = T1 * T2;
}
}
However inside the prePersist()
method all transient fields are cleared --- they are set to their initial value --- and this seems to be the proper behavior for Hibernate/Jpa.
How to overcome this?
I am using Spring boot with Jpa and Hibernate.
Upvotes: 2
Views: 616
Reputation: 23552
If you persist a new entity by calling EntityManager::persist
, then the behaviour you describe will not happen and transient fields will be visible in the @PrePersist
method.
However, if you persist a new entity with EntityManager::merge
, then the merging mechanism will ignore transient fields, which is expected behaviour - only the properties that Hibernate is aware of are merged. Keep in mind that merge
always returns a copy (except when the argument is already a managed instance), so you have to copy transient fields manually into the result of the merge
operation.
Upvotes: 1