我有一个Repository,其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 ?
答案 0 :(得分:0)
当我发布这篇文章时,我注意到了“限制?”第二个查询中的子句。我手动添加了@Query和countQuery,并没有看到更改。然后我突然意识到 - limit
的争论来自何处?
这只是一种不同的方法:
@EntityGraph(attributePaths = {"bar"})
@Override
List<Foo> findAll();
@EntityGraph(attributePaths = {"bar"})
@Override
Page<Foo> findAll(Pageable pageable);
第二个来自PagingAndSortingRepository