英文:
Spring Data JPA findAll with different EntityGraph
问题
在Spring Data JPA Repository中,我需要指定多个执行相同操作的方法(例如,findAll),但是需要指定不同的@EntityGraph注解(目标是在不同的服务中使用优化过的方法)。
例如:
@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long> {
@EntityGraph(attributePaths = { "roles" })
findAll[withRoles](Specification sp);
@EntityGraph(attributePaths = { "groups" })
findAll[withGroups](Specification sp);
// 其他方法...
}
在Java中,我们不能多次使用相同的方法签名,那么如何管理这种情况?
是否可以在不使用JPQL的情况下实现?
谢谢,
Gabriele
英文:
in Spring Data JPA Repository i need to specify multiple methods that do the same thing (eg. findAll) but specifying different @EntityGraph annotation (the goal is to have optimized methods to use in different services).
Es.
@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long> {
@EntityGraph(attributePaths = { "roles" })
findAll[withRoles](Specification sp);
@EntityGraph(attributePaths = { "groups" })
findAll[withGroups](Specification sp);
etc...
}
In Java we can't have same method sign multiple times, so how to manage it?
Is it possible without using JPQL?
Thanks,
Gabriele
答案1
得分: 5
你可以使用 EntityGraphJpaSpecificationExecutor
根据你的方法传递不同的 entitygraph
。
@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long>, EntityGraphJpaSpecificationExecutor<User> {
}
在你的服务类中,你可以调用带有实体图的查找所有操作。
List<User> users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))
就像上面的例子,你可以根据需求使用不同的实体图。
英文:
You can use EntityGraphJpaSpecificationExecutor
to pass different entitygraph
based on your method.
@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long>, EntityGraphJpaSpecificationExecutor<User> {
}
In your service class, you can call find all with entity graph.
List<User> users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))
Like above, you can use a different entity graph different based on your requirement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论