在Spring JPA中保存实体之前的业务逻辑

dre*_*nda 5 spring spring-data-jpa spring-data-rest spring-boot

我正在使用Spring Boot 1.5.4,Spring Data REST,Spring JPA,Hibernate,并且正在开发使用REST API的Angular客户端。

Spring Data REST很有帮助,我正在尝试遵循最佳实践,因此存储库类似于:

@Transactional
@PreAuthorize("isAuthenticated()")
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
}
Run Code Online (Sandbox Code Playgroud)

并自动地拥有了所有的save(),delete()和findXX()方法。那很棒。

现在,我想知道在保存实体之前是否需要自定义业务逻辑来执行。假设我需要进行某种复杂的验证(涉及对db的查询),以及其他后台活动(例如,保存相关实体,更新相关对象等)。我的目标是:

  1. 确保每次保存实体(通过REST调用或JPA调用)时,在保存对象之前都会调用我的业务逻辑
  2. 避免创建自定义存储库,因为开发人员可以调用标准存储库违反我的规则
  3. 找到一种简单的方法来保持应用程序易于维护

@RepositoryEventHandler对我来说还不够,因为我想确保始终对我的业务逻辑进行验证,即使对该方法的调用来自内部类也是如此。

您能建议我实现目标的最佳方法吗?

Abh*_*kar 8

JPA有很多实体侦听器

@PrePersist Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
@PreRemove  Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PostPersist    Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
@PostRemove Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PreUpdate  Executed before the database UPDATE operation.
@PostUpdate Executed after the database UPDATE operation.
@PostLoad   Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.
Run Code Online (Sandbox Code Playgroud)