我有以下JPA Mapping(出于简洁目的,getter和setter出来,DDL也是从可能/可能不起作用的代码生成的):
费用
@Entity
public class Expense {
@Id
@GeneratedValue
private Long id;
private String name;
private Long amount;
private Boolean monthly;
@OneToOne
@JoinColumn(name = "category")
@Fetch(FetchMode.JOIN)
private Category category;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<Label> labels = new ArrayList<>();
//constructor, getters and setters...
}
分类
@Entity
public class Category {
@Id
private String name;
//constructor, getters and setters...
}
标签
@Entity
public class Label {
@Id
private String name;
//constructor, getters and setters...
}
使用JpaRepository
所以我使用的JpaRepository看起来像这样:
public interface ExpensesRepository extends JpaRepository<Expense, Long> {
@Query("SELECT e FROM Expense e LEFT JOIN FETCH e.category")
List<Expense> findAllExpensesExploded();
}
当我使用JpaRepository的默认findAll()方法时,我得到 n + 1选择问题:
2017-01-03 19:35:22.665 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL : select expense0_.id as id1_1_, expense0_.amount as amount2_1_, expense0_.category_name as category5_1_, expense0_.monthly as monthly3_1_, expense0_.name as name4_1_ from expense expense0_
2017-01-03 19:35:22.673 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.674 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Rent]
2017-01-03 19:35:22.682 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.683 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Insurance]
但是,当我使用自己的 findAllExpensesExploded()方法时,我会得到一个SQL查询:
2017-01-03 19:35:22.691 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL : select expense0_.id as id1_1_0_, category1_.name as name1_0_1_, expense0_.amount as amount2_1_0_, expense0_.category_name as category5_1_0_, expense0_.monthly as monthly3_1_0_, expense0_.name as name4_1_0_ from expense expense0_ left outer join category category1_ on expense0_.category_name=category1_.name
我的期望是 findAll()和 findAllExpensesExploded(),用单个SQL查询执行。
答案 0 :(得分:1)
默认提取模式是懒惰的。使用Spring Data JPA时,使用@NamedEntityGraph
和@EntityGraph
注释始终是一个好习惯。您可以浏览this
whether the default findAll() should only be used for simple entities? (where simple is defined as no associations).
获取模式 - LAZY只会触发主表。如果在代码中调用任何其他具有父表依赖关系的方法,则它将触发获取模式 - SELECT。