将客户行为添加到 CDI 上下文中的所有 spring 数据 Jpa 存储库 [英] Add customer behaviour to all spring data Jpa repositories in CDI context

查看:38
本文介绍了将客户行为添加到 CDI 上下文中的所有 spring 数据 Jpa 存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CDI 成功注入了 jpa 存储库.我想向所有存储库添加自定义行为(软删除).使用 spring 时,我可以通过指定存储库基类来启用客户行为

Am successfully injecting jpa repositories using CDI. I wanted to add custom behaviour(soft deletes) to all repositories. When using spring I can enable customer behaviour by specifying the repository base class

@EnableJpaRepositories(repositoryBaseClass = StagedRepositoryImpl.class)

如何在 CDI 中指定相同的内容?提前致谢.

How do I specify the same in CDI? Thanks in advance.

推荐答案

要将自定义行为添加到 Jpa 存储库(在您的情况下是删除),

To add custom behaviour to Jpa Repositories(in your case for delete),

1. 创建一个如下所示的基本存储库:

1. Create a base repository like below:

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {

    @Override
    default void delete(T entity){
        // your implementation
    }
}

2. 现在从自定义存储库(即 BaseRepository)继承 Jpa 存储库,如下所示:

2. Now inherit Jpa Repositories from custom repository(i.e BaseRepository) like below:

public interface EmployeeRepository extends BaseRepository<Employee, Long> {
}

3. 将您的存储库注入 Service 类并调用 delete 方法.

3. Inject your repository into Service class and call the delete method.

@Service
class EmployeeService {

    @Inject
    private EmployeeRepository employeeRepository;

    public void delete(Long id) {
        employeeRepository.delete(id);
    }
}

现在,每当您对 BaseRepository 的子存储库调用 delete 时,您的自定义删除实现都会被调用.

Now whenever you call delete on repositories which are child of BaseRepository, your custom implementation for delete will be invoked.

这篇关于将客户行为添加到 CDI 上下文中的所有 spring 数据 Jpa 存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆