JPA + Hibernate - 如何在不获取子实体的情况下获取子实体的 FK?

Ant*_*sss 5 java hibernate jpa

我的问题的可能答案位于此处: How can I检索外键从JPA ManyToOne映射而不命中目标表?

但是,更好的解决方案(属性访问)在我的情况下不起作用(我缺少列异常 - 为什么?)

该模型如下所示:实体ParentChild。表具有表的parentchild_id,因此它是典型的关系。PKchild@ManyToOne

现在的重点是,如果我获取实体,我需要在不获取实体的情况下Parent访问FK值(也称为实体)。我怎样才能做到这一点?PKChildChild

我使用Annotations并且我的映射如下所示:

@Entity
@Table(name = "parent")
public class Parent extends AbstractEntity {

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "patent_id", nullable = true)
private Child child;

@Column(name="child_id",insertable=false,updatable=false)
private Integer childId;

public Child getChild() {
    return patent;
}

public void setChild(Child child) {
    this.child = child;
}


public Integer getChildId(){
    return childId;
}
}
Run Code Online (Sandbox Code Playgroud)

我想做的是调用parent.getChild().getId()而不需要从数据库中额外获取Child实体。

根据我上面提到的答案,如果我将注释从字段移动到 getter(在Parent实体中我是对的吗?),请求的行为将是开箱即用的。然而,当我将注释移动到 getter 时,我收到一个验证异常,该child列缺失(奇怪,为什么childchild_id按照声明的那样?)

PS:显示的将FK列声明为单独字段的解决方法可以正常工作,但我认为这不是应该完成的方式。

Ant*_*sss 0

好的,在阅读以下文章http://256stuff.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml后 我意识到,属性访问应该是我想要获取的属性,而不是实际的child对象。因此,将字段id的访问权限更改为属性的权限就可以了。AbstractEntity