3

在 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);

etc...
}

在Java中我们不能多次签名相同的方法,那么如何管理呢?

不使用JPQL可以吗?

谢谢,

加布里埃尔

4

1 回答 1

2

您可以使用根据您的方法EntityGraphJpaSpecificationExecutor传递不同的方法。entitygraph

@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long>, EntityGraphJpaSpecificationExecutor<User> {

}

在您的服务类中,您可以使用实体图调用 find all。

List<User> users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))

像上面一样,您可以根据您的要求使用不同的实体图。

于 2020-05-04T03:53:30.430 回答