JPA @OneToOne选择包含N + 1个查询的列表

时间:2017-12-11 13:56:07

标签: performance hibernate jpa one-to-one select-n-plus-1

我实际上是尝试使用JPA @OneToOne注释将Child实体链接到其Parent

它运行良好,除了获得Child列表时,JPA引擎(本例中为Hibernate)进行1 + n次查询。

以下是Hibernate查询的日志:

select child0_.id as id1_0_, child0_.parent as parent3_0_, child0_.value as value2_0_ from child child0_
select parent0_.id as id1_1_0_, parent0_.something as somethin2_1_0_ from parent parent0_ where parent0_.id=?
select parent0_.id as id1_1_0_, parent0_.something as somethin2_1_0_ from parent parent0_ where parent0_.id=?
select parent0_.id as id1_1_0_, parent0_.something as somethin2_1_0_ from parent parent0_ where parent0_.id=?

使用完全相同的实体定义,当我特别得到一个孩子时,JPA会使用预期的JOIN执行查询:

select child0_.id as id1_0_0_, child0_.parent as parent3_0_0_, child0_.value as value2_0_0_, parent1_.id as id1_1_1_, parent1_.something as somethin2_1_1_ from child child0_ left outer join parent parent1_ on child0_.parent=parent1_.id where child0_.id=?

以下是Child实体定义:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "child")
public class Child {

    @Id
    private Long   id;
    @Column
    private String value;
    @OneToOne(optional = false)
    @JoinColumn(name = "parent")
    private Parent parent;

}

Parent实体:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "parent")
public class Parent {

    @Id
    private Long   id;
    @Column
    private String something;

}

您可以在此处找到运行代码的完整示例: https://github.com/Alexandre-Carbenay/demo-jpa-onetoone

在获取Child Parent实体列表时,有没有办法避免1 + n次查询?

3 个答案:

答案 0 :(得分:1)

我终于找到了一个比JOIN FETCH更好的解决方案,它也适用于QueryDsl,在存储库方法上使用@EntityGraph注释。

以下是更新的Child定义:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@NamedEntityGraph(name = "Child.withParent", attributeNodes = @NamedAttributeNode("parent"))
@Table(name = "child")
public class Child {
    @Id
    private Long   id;
    @Column
    private String value;
    @OneToOne(optional = false)
    @JoinColumn(name = "parent")
    private Parent parent;
}

ChildJpaRepository定义:

public interface ChildJpaRepository extends JpaRepository<Child, Long>, QueryDslPredicateExecutor<Child> {

    @Override
    @EntityGraph("Child.withParent")
    List<Child> findAll();

    @Override
    @EntityGraph("Child.withParent")
    List<Child> findAll(Predicate predicate);

}

感谢Simon Martinelli和Vlad Mihalcea的帮助

答案 1 :(得分:0)

我可以重现你的观察结果,但我认为Hibernate没有理由这样做。

避免查询的解决方案是使用JOIN FETCH,如

select c from Child c join fetch c.parent

答案 2 :(得分:0)

正如我在this article中所解释的那样,默认情况下,@OneToOne@ManyToOne关联使用FetchType.EAGER,这就是您看到N+1 query issue的原因}。

所以,解决方案非常简单,只需将获取策略设置为LAZY:

@OneToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "parent")
private Parent parent;

如果您具有双向@OneToOne关联,则除非使用字节码增强,否则不能使父级变为惰性。有关详细信息,请查看我的High-Performance Java Persistence书籍。