被@Prepersist注解的方法 ,完成save之前的操作。
被@Preupdate注解的方法 ,完成update之前的操作。
被@PreRemove注解的方法 ,完成remove之前的操作。
被@Postpersist注解的方法 ,完成save之后的操作。
被@Postupdate注解的方法 ,完成update之后的操作。
被@PostRemovet注解的方法 ,完成remove之后的操作。
自定义实体类监听类:
import org.springframework.stereotype.Component;
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
public class TestEntityListeners {
@PrePersist
public void PrePersist(Object entity){
System.out.println("开始保存--"+entity.toString());
}
@PreUpdate
public void PreUpdate(Object entity){
System.out.println("开始更新--"+entity.toString());
}
@PostPersist
public void PostPersist(Object entity){
System.out.println("结束保存--"+entity.toString());
}
@PostUpdate
public void PostUpdate(Object entity){
System.out.println("结束更新--"+entity.toString());
}
}
实体类上增加注解:@EntityListeners(value = {TestEntityListeners.class})
@Entity
@Table(name = "product")
@EntityListeners(value = {TestEntityListeners.class})
public class Product {
private int id;
private String productId;
private String productName;
//getter setter toString()
写两个测试保存、更新的方法:
import com.goods.evaluate.entity.Product;
import com.goods.evaluate.service.TestService1;
import com.goods.evaluate.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
public class TestService implements TestService1 {
@Autowired
private ProductRepository productRepository;
@Transactional
public void testSave(){
Optional<Product> product = productRepository.findById(10);
productRepository.save(product.orElse(null));
System.out.println("保存。。。");
}
@Transactional
public void testUpdate(){
productRepository.updateProduct("test10");
System.out.println("更新。。。");
}
}
执行结果:
这是Application的配置:
@SpringBootApplication
@EnableSpringConfigured
@EnableJpaAuditing
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class EvaluateApplication {
public static void main(String[] args) {
SpringApplication.run(EvaluateApplication.class, args);
}
}