【发布时间】:2011-04-13 19:16:20
【问题描述】:
我的 Hibernate 实体看起来像这样(getter 和 setter 被忽略了):
@Entity
public class EntityA {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private EntityB parent;
}
@Entity
public class EntityB extends SuperEntity {
@OneToMany(mappedBy = "parent")
@Fetch(FetchMode.SUBSELECT)
@JoinColumn(name = "parent_id")
private Set<EntityA> children;
}
@MappedSuperclass
public class SuperEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long itemId;
}
当我查询 EntityA 时,它加载正常,父关联被 Hibernate 代理替换(因为它是 Lazy)。如果我想访问父母的 id,我执行以下调用:
EntityA entityA = queryForEntityA();
long parentId = entityA.getParent().getItemId();
据我了解,调用不应往返于数据库,因为 Id 存储在 EntityA 表中,并且代理应该只返回该值。但是,在我的情况下,这会生成一个获取 EntityB 的 SQL 语句,然后才返回 Id。
如何调查问题?这种不正确行为的一些可能原因是什么?
【问题讨论】:
标签: java hibernate orm proxy lazy-loading