gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:43:41 25 4
gpt4 key购买 nike

我正在使用 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> {
}

并且自动地我拥有了所有的 save()、delete()、findXX() 方法。太好了。

现在我想知道在保存实体之前是否需要自定义业务逻辑如何执行。假设我需要进行某种复杂的验证(涉及数据库查询)和其他后台事件(可能保存相关实体、更新相关对象等)。我的目标是:

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

@RepositoryEventHandler 对我来说还不够,因为我想确保我的业务逻辑始终得到验证,即使对方法的调用来自内部类。

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

最佳答案

JPA 有一堆 entity listener .

@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.

关于spring - 在 Spring JPA 中保存实体之前的业务逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com