我实际上是在尝试使用 JPA@OneToOne
注释将Child
实体链接到它的Parent
.
它运行良好,除了在获取Child
s 列表时,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
获取实体列表时有没有办法避免 1+n 查询Parent
?