JPA解决N+1问题(指查询对象A,结果把A中的子对象B、C等也查询出来),我们可以使用EntityGraph。
@NamedEntityGraph(
name = "aWithBWithC",
attributeNodes = {
@NamedAttributeNode(value = "bs", subgraph = "bWithC"),
@NamedAttributeNode("c"),},
subgraphs = {
@NamedSubgraph(name = "bWithC",
attributeNodes = {@NamedAttributeNode("cs")})
}
)
@Entity
@Table(name = "a", catalog = "funny", schema = "testing")
public class A {
@OneToMany//默认懒加载
@JoinTable( //if you have a table a_b for this relationship. Not related to the topic of entityGraph though.
name = "a_b",
joinColumns = @JoinColumn(name = "a_id"),
inverseJoinColumns = @JoinColumn(name = "b_id")
)
private Set<B> bs;
@OneToOne //默认及时加载
@JoinColumn(unique = true)
private C c;
}
public interface AsRepository extends PagingAndSortingRepository<A, Long> {
@EntityGraph(value = "aWithBWithC", type = EntityGraph.EntityGraphType.FETCH)
Page<Item> findAll(Pageable pageable); //FETCH will load all nested entity in one query.
}