具有多个实体查找器的通用Spring JPA存储库 [英] Common spring jpa repository with multiple entity finders
问题描述
我的应用程序有250多个表,每个表都有ID和名称列.我正在尝试将我们的应用程序从休眠3迁移到带有休眠5+的Spring-JPA 4.3.
My application has over 250 tables with each having ID and name columns. I am trying to migrate our application from hibernate 3 to Spring-JPA 4.3 with hibernate 5+.
在我当前的休眠层中,我有(选项1):
In my current hibernate layer I have (Option 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;
}
}
过去我可以使用更通用的方法来完成以下操作,但是如果我有10个要通过ID提取的不同实体,我就不想重新初始化此类.
Back in the days i could have done the following with more generic methods but I didn't want to reinitialize this class if i have 10 different entities to fetch by 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;
}
}
现在我如何在Spring-JPA中实现这一目标.因此,如果我需要通过ID获取10个不同的实体,我不想初始化10个存储库,那么我想拥有一个存储库,我可以使用该存储库来获取想要的所有实体,这些实体需要byId或byName或byIDAndName.我可以使用JdbcTemplate轻松做到这一点,但这意味着JPA/休眠缓存机制可能无法跟踪它.
Now how can i achieve this in Spring-JPA. So If i need to get 10 different entities by ID, i don't want to initialize 10 repositories, i want to have one repository that i can use to fetch any entity i want byId or byName or byIDAndName. I could do it easily with JdbcTemplate but that means it may not be tracked by JPA/hibernate caching mechanism.
那么如何在一个JPA存储库中执行以下操作:
So how can do the following in one JPA repository:
{
@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);
}
推荐答案
您应该能够创建具有公共属性的超类,将其标记为@MappedSuperClass并为该超类创建存储库为@NoRepositoryBean.您只需要对结果进行一些转换即可. 参见此答案
You should be able to create a super class(es) that has the common attributes, mark it as a @MappedSuperClass and create a repository for that super class as @NoRepositoryBean. You'll just have to do some casting for your results. See this answer
这篇关于具有多个实体查找器的通用Spring JPA存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!