【问题标题】:NamedEntityGraph ignore in Spring Data RestSpring Data Rest 中的 NamedEntityGraph 忽略
【发布时间】:2018-06-04 11:17:22
【问题描述】:

我有一个存储库,它的 findAll 方法标有@EntityGraph。我正在将生成的 SQL 打印到日志中,我可以看到它在 Java 中直接使用时会生成正确的连接选择(即myRepo.findAll();)。 但是当我通过 REST 调用它时,这不会发生。我要么得到一个例外,公元前。 Lazy-Loading 代理无法序列化,或者如果我添加 jackson-databind-hibernate5,我可以看到其他查询。

我已尝试在此处生成最小复制:https://github.com/cptwunderlich/SpringDataRestDemo

我看不到额外的查询,也没有异常,所以我怀疑实体已经在缓存中,但是它发出了一个没有连接的选择。

这里是代码的摘录(使用 lombok 生成的 getters/setters/etc,为简洁起见省略了一些样板!):

实体:

@Entity
@Data
@NoArgsConstructor(force = true)
public class Bar {
  @Id @GeneratedValue
  private Long id;

  private String value;

  @Version
  private Long version;
}

@Entity
@NamedEntityGraph(name = "Foo.full", includeAllAttributes = true)
@Data
@NoArgsConstructor(force = true)
@EqualsAndHashCode(of = {"name"})
public class Foo {
  @Id @GeneratedValue
  private Long id;

  private String name;

  @ManyToOne(fetch = LAZY, cascade = CascadeType.ALL)
  @NonNull
  private Bar bar;

  @Version
  private Long version;
}

存储库:

@RestResource
public interface FooRepository extends JpaRepository<Foo, Long> {

  @EntityGraph(value = "Foo.full", type = EntityGraphType.LOAD)
  @Override
  List<Foo> findAll();
}

为 findAll 生成的查询:

select
    foo0_.id as id1_1_0_,
    bar1_.id as id1_0_1_,
    foo0_.bar_id as bar_id4_1_0_,
    foo0_.name as name2_1_0_,
    foo0_.version as version3_1_0_,
    bar1_.value as value2_0_1_,
    bar1_.version as version3_0_1_ 
from
    foo foo0_ 
left outer join
    bar bar1_ 
        on foo0_.bar_id=bar1_.id

通过 REST 查询:

select
    foo0_.id as id1_1_,
    foo0_.bar_id as bar_id4_1_,
    foo0_.name as name2_1_,
    foo0_.version as version3_1_ 
from
    foo foo0_ limit ?

【问题讨论】:

  • 当我发布这个时,我注意到第二个查询中的“limit”子句。 Spring Data Rest 是否有可能应用分页并以某种方式干扰连接?

标签: java spring jpa spring-data spring-data-rest


【解决方案1】:

天哪,我刚刚想通了。我想是一种橡皮鸭调试形式。

当我发布此内容时,我注意到“限制?”第二个查询中的子句。我手动添加了 @Query 和 countQuery 并没有看到任何变化。然后我恍然大悟——limit 的论点从何而来?

这只是一种不同的方法:

  @EntityGraph(attributePaths = {"bar"})
  @Override
  List<Foo> findAll();

  @EntityGraph(attributePaths = {"bar"})
  @Override
  Page<Foo> findAll(Pageable pageable);

第二个来自 PagingAndSortingRepository

【讨论】:

    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 2014-12-19
    • 2019-07-02
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2015-06-23
    相关资源
    最近更新 更多