【问题标题】:JPA + Hibernate - How to get FK of child entity without fetching that entity?JPA + Hibernate - 如何在不获取该实体的情况下获取子实体的 FK?
【发布时间】:2014-11-11 04:18:09
【问题描述】:

我的问题的可能答案位于此处: How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?

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

模型如下所示:实体ParentChild。表 parent 的列 child_idPKchild 表,因此它是典型的 @ManyToOne 关系。

现在的重点是,如果我获取Parent 实体,我需要访问FK 值(又名PKChild 实体)而不获取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/…

标签: java hibernate jpa


【解决方案1】:

好的,看完下面的文章http://256stuff.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml 我已经意识到,属性访问应该是我想要获取的属性,而不是实际的 child 对象。因此,将 AbstractEntityid 访问权限从字段更改为属性,就成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2016-07-11
    • 1970-01-01
    相关资源
    最近更新 更多