想象一下这个数据模型:
@Entity
@Data
public class A {
@Id
long id;
@ManyToOne
@JoinColumn
@NotFound(action = NotFoundAction.IGNORE)
B b;
}
@Entity
@Data
public class B {
@Id
long id;
}
现在想象以下数据(是的,它在数据库中不一致):
A
id | b_id
---------
1 | 1
2 | 2
B
id
---
1
如您所见,A#2的FK到B#2实际上是缺失的。
这使得Hibernate执行额外的SELECT请求以检查它是否实际丢失,尽管它已经在发出SELECT A LEFT JOIN B请求时发现了该请求。是否有可能以某种方式阻止执行此附加请求?
当我拿A#1时会发生什么:
2018-01-17 18:43:05.545 DEBUG 5332 --- [ main] org.hibernate.SQL : select a0_."id" as id1_0_0_, a0_."b_id" as b_id2_0_0_, b1_."id" as id1_1_1_ from TEST.A a0_ left outer join TEST.B b1_ on a0_."b_id"=b1_."id" where a0_."id"=?
2018-01-17 18:43:05.555 TRACE 5332 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [1]
2018-01-17 18:43:05.561 TRACE 5332 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([id1_1_1_] : [BIGINT]) - [1]
2018-01-17 18:43:05.565 TRACE 5332 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([b_id2_0_0_] : [BIGINT]) - [1]
对于A#2而言:
2018-01-17 18:42:13.597 DEBUG 5283 --- [ main] org.hibernate.SQL : select a0_."id" as id1_0_0_, a0_."b_id" as b_id2_0_0_, b1_."id" as id1_1_1_ from TEST.A a0_ left outer join TEST.B b1_ on a0_."b_id"=b1_."id" where a0_."id"=?
2018-01-17 18:42:13.605 TRACE 5283 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [2]
2018-01-17 18:42:13.611 TRACE 5283 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([id1_1_1_] : [BIGINT]) - [null]
2018-01-17 18:42:13.615 TRACE 5283 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([b_id2_0_0_] : [BIGINT]) - [2]
2018-01-17 18:42:13.617 DEBUG 5283 --- [ main] org.hibernate.SQL : select b0_."id" as id1_1_0_ from TEST.B b0_ where b0_."id"=?
2018-01-17 18:42:13.617 TRACE 5283 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [2]
答案 0 :(得分:0)
您可以在查询中尝试JOIN FETCH
,而不是简单的JOIN
。 @ManyToOne
关联的默认行为是急切的,除非您将其指定为LAZY,因此我不知道为什么会发生这种情况。无论如何,获取连接应解决它。