Spring Data JPA使用不同的EntityGraph进行findAll

8
在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实现?

谢谢,

Gabriele


你可以将 EntityGraph 作为参数使用:https://dev59.com/V6zka4cB1Zd3GeqP6U2N - Olivier Depriester
太好了,我不知道你可以将实体图作为参数传递!谢谢! - Gabriele Muscas
2个回答

5

您可以使用EntityGraphJpaSpecificationExecutor在方法中传递不同的entitygraph

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

}

在你的服务类中,你可以使用实体图调用findAll。
List<User> users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))

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


谢谢,你的回答对我非常有帮助。谢谢! - Gabriele Muscas
你可以接受答案,这样其他人就知道了。 - SSK
我似乎找不到 EntityGraphJpaSpecificationExecutor,你从哪里得到它的? - La Hai
1
@La Hai,你需要从https://mvnrepository.com/artifact/com.cosium.spring.data/spring-data-jpa-entity-graph/2.4.2添加它的依赖项。 - SSK

0
你可以在你的存储库中创建两个具有相同签名的默认方法,就像这样:
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long> {

    @EntityGraph(attributePaths = { "roles" })
    default List<Roles> findAllByRoles(Specification sp){
       return findAll(sp);
    }

    @EntityGraph(attributePaths = { "groups" })
    default List<Roles> findAllByGroups(Specification sp){
       return findAll(sp);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接