Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSave() (for any Entity saved with Hibernate/Spring Data Repositories)

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()?

like image 640
Paul Verest Avatar asked Jun 16 '16 15:06

Paul Verest


People also ask

What is the method name to save data for a entity to database in repository?

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.

What happens if the argument for Save () method of CrudRepository is null?

So if the field is null in the entity to save , it will overwrite its value to null in the existing row.

How do I stop Spring data JPA from doing a select before a save ()?

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.

What is difference between save and saveAndFlush?

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.


1 Answers

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

like image 130
Koitoer Avatar answered Oct 04 '22 22:10

Koitoer