简体   繁体   中英

Spring boot - operation before repository save

I'm supporter one code that have a lot of spread

dummyRepository.save(dummy)

but I need do some operations with "dummy" object before save, how can I do this?

你可以使用 Spring AOP 进行这种篡改

I would have a look at the annotations of the Java Persistence API (JPA):

@PrePersist 

Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.

and

@PreUpdate

Executed before the database UPDATE operation.

There are various ways to use them:

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

The easiest way is to just add a Method in your Entity with this annotation. For example:

 @PrePersist
 @PreUpdate
 protected void onCreateOrUpdate()
 {
     setLastChangeDate(new Date());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM