【发布时间】:2014-11-11 04:18:09
【问题描述】:
我的问题的可能答案位于此处: How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
但是,在我的情况下,更可取的解决方案(属性访问)不起作用(我得到了缺少列异常 - 为什么?)
模型如下所示:实体Parent 和Child。表 parent 的列 child_id 是 PK 的 child 表,因此它是典型的 @ManyToOne 关系。
现在的重点是,如果我获取Parent 实体,我需要访问FK 值(又名PK 的Child 实体)而不获取Child 实体。我该怎么做?
我使用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;
}
}
我想要做的是调用parent.getChild().getId(),而不需要从数据库中额外获取Child 实体。
根据我上面提到的答案,如果我将注释从字段移动到 getter(在 Parent 实体中,我对吗?),请求的行为将是开箱即用的。但是,当我将注释移动到 getter 时,我得到一个验证异常,即缺少 child 列(好奇,为什么 child 不是 child_id 声明的那样?)
PS: 将FK 列声明为单独字段的解决方法可以正常工作,但我认为这不是应该的方式。
【问题讨论】:
-
我认为当您执行延迟加载休眠时,甚至不获取该列。因此,如果您希望它在不获取的情况下显示,您应该使用本机查询。
-
不是选项,我使用
Criteria API -
尝试@Formula 注释并输入您想要的内容。可能会奏效。未测试
-
@dinesh707 这不是 JPA 注释
-
org.hibernate.annotations.Formula; stackoverflow.com/questions/2986318/…