当前位置: 首页 > 知识库问答 >
问题:

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

施令秋
2023-03-14

我正在使用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调用)时,都会在保存对象之前调用我的业务逻辑

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

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

共有1个答案

宋昊然
2023-03-14

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.
 类似资料:
  • 我有一个方法,它调用另一个方法来保存具有新事务的实体对象。 process()正在调用FooCreator类中的createFoo()方法,以使用@Transactional(传播=传播。需要\u NEW)创建foo对象。 在process方法中修改返回的foo对象时,它会另存为新对象。如何修改createFoo()返回的现有foo对象? 如果我尝试findById,它仍会引发异常。 如何在新事务

  • 下面是一个场景,我正在使用Spring Data JPA保存一个实体(我们将其称为CG实体)。在这个CG实体中,我们有很多实体一一,一多和M-M,在这些实体中,有更多的关系等等。我正在通过主键设置CG实体,并向其添加其他实体对象。所以基本上,这个CG实体PK应该作为FK来使用CG中的大多数其他实体。 有些实体是新的,有些实体是通过创建具有给定主Id的对象来设置的(因此不需要使用相关的存储库来查找和

  • 因此,每个功能区显然都在数据库中,但它们还需要一些逻辑来确定用户何时获得了功能区。 按照我的编码方式,是一个简单的接口: 是一个抽象类,它实现了接口,避免了方法的定义: 现在,将像这样实现一个特定的功能区: 这段代码工作得很好,表是按照我期望的方式在数据库中创建的(我在本地环境中使用DDL生成)。 问题是,在域对象中编写业务逻辑感觉是错误的。这是好的练习吗?你能提出一个更好的解决方案吗?此外,我不

  • 我在删除联接表中引用的实体时遇到问题。以下是三个链接的enitie。 当我尝试使用CrudRepository从来宾表中删除来宾时,它会给我这个错误。 错误:表“guest”上的更新或删除违反了表“guest\u group\u join”上的外键约束“FKKOUGVMCU860MOUACR1SHJXY”。键(id)=(4)仍然从表“guest\u group\u join”中引用。 有人能帮忙吗

  • 我们的业务逻辑代码主要在 controllers 目录中,新建一个 todo.py 文件, 核心代码如下 (完整代码参考这里),代码说明可以参考注释: # -*- coding: utf-8 -*- import flask from flask import request, redirect, flash, render_template, url_for from application.e

  • 所以它不是一个简单的逻辑,而是一个复杂的逻辑。由于这种逻辑可以在许多不同的存储过程中重复,因此可以在数据库中使用一个单独的函数,以避免重复代码。 那么,这里推荐的方式是什么呢?那为什么呢?