【发布时间】:2018-05-25 01:39:03
【问题描述】:
我实际上是在尝试使用 JPA @OneToOne 注释将 Child 实体链接到其 Parent。
它运行良好,除了在获取Childs 列表时,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
在获取带有Parent 的Child 实体列表时,有没有办法避免1+n 查询?
【问题讨论】:
-
父母是强制性的吗?如果是,则在 OneToOne 注释中设置 optional=false。
-
我试过添加这个 optional=false,但它并没有改变任何东西
标签: performance hibernate jpa one-to-one select-n-plus-1