If my Entity has calculated fields should be updated before saving to database (db insert
or update
),
How can I hook a method call before Hibernate or Spring Data Repository save()
?
CrudRepository save() to Add a New Instance The instance is initially created with a null value for its id, and when we call the save() method, an id is automatically generated. The save() method returns the saved entity, including the updated id field.
So if the field is null in the entity to save , it will overwrite its value to null in the existing row.
The solution is to use @javax. persistence. Version on a new versionNumber column in all the tables. If you have a parent and child table then use @Version column in all the entity classes.
Save and saveAndFlush both can be used for saving entities. They both are both belong to the Spring data library. save may or may not write your changes to the DB straight away. When we call saveAndFlush system are enforcing the synchronization of your model state with the DB.
I think the best option for you are EntityListener
using the @PrePersist
and @PreUpdate
annotations, create the configuration for your entity listener and you will get access to each instance that you want to save, this method is being called each time you are trying to persist or update something with hibernate or spring data repositories
public class EntityToPersistListener{
@PrePersist
@PreUpdate
public void methodExecuteBeforeSave(final EntityToPersist reference) {
//Make any change to the entity such as calculation before the save process
reference.setAmount(xxxx)
}
}
You just need to add an annotation above your entity bean
@Entity
@Table(name = "", schema = "", catalog = "")
@EntityListeners(EntityToPersistListener.class)
public class EntityToPersist implements Serializable {
Check this link for further reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With