【问题标题】:Business logic before to save an entity in Spring JPA在 Spring JPA 中保存实体之前的业务逻辑
【发布时间】:2017-12-17 06:42:30
【问题描述】:

我正在使用 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 对我来说还不够,因为我想确保我的业务逻辑始终得到验证,即使对方法的调用来自内部类。

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

【问题讨论】:

  • 您好!关于使用 AOP - 也许this 会有所帮助...

标签: spring spring-boot spring-data-jpa spring-data-rest


【解决方案1】:

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 AOP 会更好?
  • @drenda 您在问题中没有提到您知道实体侦听器。您要求一种在数据库操作之前执行业务逻辑的方法。如果您的问题是选择众多设计中的一种,那么这是错误的论坛。如果我是你,我会避免通过为已经存在的内容编写 AOP 来重新发明轮子。
  • 我没有提到我也知道 AOP。我没有要求一种方法来做到这一点,考虑到我必须进行查询和复杂的业务逻辑,我要求最好的方法,我不想做“气馁”的事情。我不同意你的看法:这个论坛也非常有助于从开发人员那里获得帮助以使用最佳实践;很多时候开发库的人阐明了如何以最佳方式使用它。谢谢对于您的回复,但也许可能是比我更专家的人,并且您对此用例有更多/不同的考虑,这对其他人也可能有用。
  • @drenda,这个论坛专门讨论特定的技术问题,而不是教学设计问题。肯定有这样的讨论的地方,但事实并非如此。这与我知道或不知道多少无关。
猜你喜欢
  • 1970-01-01
  • 2021-02-14
  • 2019-11-03
  • 2013-11-29
  • 1970-01-01
  • 2011-04-15
  • 2015-11-07
  • 2012-01-12
  • 1970-01-01
相关资源
最近更新 更多