如何重写 Spring Data JPA 存储库基本方法?

Raf*_*zcz 3 java spring hibernate spring-data-jpa

我有一些实体类型需要额外的保存逻辑(准确地说,我想在保存时保存位置)。我不想使用任何特定于数据库的功能(例如触发器)来执行此操作,因为我不确定将来使用的数据存储是什么。

所以我想重写save()方法。

在 Spring Data JPA 文档中,我可以看到两种为存储库类提供自己的实现的方法:

  1. 扩展基础存储库类并告诉 Spring Data 使用它。
  2. PositionedRepository使用实现类 ( )定义一个接口(在我的例子中我假设为) PositionedRepositoryImpl

第一种方法的问题 - 我不想为所有存储库实现它,只定位两种实体类型。

第二种方式的问题 - 我无法访问基本存储库方法,因此除了位置计算之外,我还需要以某种方式构建通常由基本存储库提供的所有查询。

有什么方法可以仅针对特定存储库类型扩展基本存储库类吗?

Lin*_*ica 5

不要在存储库本身中执行该逻辑。将存储库视为 java 和数据库之间的哑层。它只是将数据从一端传递到另一端。

相反,您应该在不同的层中处理这种情况。更聪明的一个。业务逻辑层。

看这个例子:

@Service
public class MyEntityService{

     private final MyEntityRepository myEntityRepository;
     private final OtherEntityRepository otherEntityRepository;

     @Autowired
     public MyEntityService(MyEntityRepository myEntityRepository, 
                          OtherEntityRepository otherEntityRepository){
         this.myEntityRepository = myEntityRepository;
         this.otherEntityRepository = otherEntityRepository;
     }

     public void save(MyEntity myEntity){
          // do stuff with otherEntityRepository
          myEntitiyRepository.save(myEntity);
     }
}
Run Code Online (Sandbox Code Playgroud)