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

huangapple go评论88阅读模式
英文:

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&lt;User&gt;, JpaRepository&lt;User, Long&gt; {

@EntityGraph(attributePaths = { &quot;roles&quot; })
findAll[withRoles](Specification sp);

@EntityGraph(attributePaths = { &quot;groups&quot; })
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&lt;User&gt;, JpaRepository&lt;User, Long&gt;, EntityGraphJpaSpecificationExecutor&lt;User&gt; {

}

In your service class, you can call find all with entity graph.

List&lt;User&gt; users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, &quot;graphName&quot;))

Like above, you can use a different entity graph different based on your requirement.

huangapple
  • 本文由 发表于 2020年5月4日 07:29:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/61582986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定