具有多个实体查找器的通用 spring jpa 存储库

San*_*nnu 5 spring hibernate spring-data-jpa spring-boot

我的应用程序有超过 250 个表,每个表都有 ID 和名称列。我正在尝试使用 hibernate 5+ 将我们的应用程序从 hibernate 3 迁移到 Spring-JPA 4.3。

在我当前的休眠层中,我有(选项 1):

public class DAO
{
    private Session session;

    public DAO(Session session)
    {
        this.session=session;
    }

    public EntityA findById(String id)
    {
        //implementation
        return entityA;
    }
    public EntityB findByName(String name)
    {
        //implementation
        return entityB;
    }
    public EntityC findByIdAndName(String id, String name)
    {
        //implementation
        return entityC;
    }
}
Run Code Online (Sandbox Code Playgroud)

回到过去,我可以使用更通用的方法完成以下操作,但如果我有 10 个不同的实体要通过 ID 获取,我不想重新初始化此类。

public class DAO<T>
{
    public T findById(String id)
    {
        //implementation
        return T;
    }
    public T findByName(String name)
    {
        //implementation
        return T;
    }
    public T findByIdAndName(String id, String name)
    {
        //implementation
        return T;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我如何在 Spring-JPA 中实现这一点。因此,如果我需要通过 ID 获取 10 个不同的实体,我不想初始化 10 个存储库,我想要一个存储库,我可以使用它来获取我想要 byId 或 byName 或 byIDAndName 的任何实体。我可以使用 JdbcTemplate 轻松完成,但这意味着 JPA/hibernate 缓存机制可能无法跟踪它。

那么如何在一个 JPA 存储库中执行以下操作:

{
    @Query("from EntityA where id=?1")
    EntityA findEntityAById(String id);

    @Query("from EntityB where name=?1")
    EntityB findEntityBById(String name);

    @Query("from EntityC where id=?1 and name=?2")
    EntityC findEntityCById(String id,String name);
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*gio 3

您应该能够创建一个具有公共属性的超类,将其标记为@MappedSuperClass,并为该超类创建一个存储库作为@NoRepositoryBean。您只需要对结果进行一些转换即可。看这个答案