我可以使用EntityGraph进行EAGER关联LAZY吗?

问题描述 投票:0回答:1

比如我有

class Foo {
  @OneToOne(fetch = FetchType.EAGER)
  Bar bar;
}

在某些查询中我不想加载栏。

我找到了解决这个问题的方法:

interface FooRepository extends JpaRepository<Foo, Long> {
  @EntityGraph(type = EntityGraph.EntityGraphType.FETCH, attributePaths = "id")
  Optional<Employee> findReducedById(Long id);
}

@EntityGraph(type = EntityGraph.EntityGraphType.FETCH, attributePaths = "id")
- 提供了我想要的,但它看起来像一个黑客
attributePaths = {} or attributePaths = {""} or attributePaths = ""
不起作用。

java spring spring-boot hibernate jpa
1个回答
0
投票

我想正确执行此操作的最佳方法是使用

@NamedEntityGraph
:

@NamedEntityGraph(name = Foo.FOO_RESTRICTED, attributeNodes = {})
class Foo {
  ... String FOO_RESTRICTED = "Foo.Restricted";

  @OneToOne(fetch = FetchType.EAGER)
  ... Bar bar;
}

和存储库:

interface FooRepository extends JpaRepository<Foo, Long> {
  @EntityGraph(Foo.FOO_RESTRICTED)
  Optional<Employee> findReducedById(Long id);
}
© www.soinside.com 2019 - 2024. All rights reserved.