【问题标题】:Writing generic spring jpa repository for all entities为所有实体编写通用 spring jpa 存储库
【发布时间】:2019-05-10 11:41:22
【问题描述】:

我正在开发 Spring Boot 应用程序。

我们有 Service Layer、Rest Controller 和 Dao 作为存储库。

我的数据库中有 20 到 30 个表,我不想为每个实体创建存储库并将其扩展到 CrudRepository。

ex : 用户是一个实体,要对用户执行持久性操作,我必须创建扩展 CrudRepository 的 UserRepository。

部门、公司等...

我想要做的是,我将编写一个 BaseRepository 来扩展 CrudRepository,基础存储库应该接受所有实体并进行持久化操作。

有办法吗??

【问题讨论】:

  • 你只会让你所有的代码更难写、更难读、更难测试,当然你不能再在 DAO 中写任何非泛型查询,只是避免创建几个类。使用该工具,一切都会变得更简单、更干净。

标签: spring spring-data-jpa


【解决方案1】:

不要扩展 CrudRepository,它的功能都与泛型类型相关,将其扩展为泛型实现会很麻烦。您可能只想要一些简单的东西,直接使用 JPA 实体管理器:

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;

public class GenericRepository {

    @Autowired
    private EntityManager entityManager;

    public <T, ID> T findById(Class<T> type, ID id) {
        return entityManager.find(type, id);
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2020-09-09
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多