如何在不提取完整实体的情况下获取从属Hibernate实体的外键列值? [英] How do I get the foreign key column value of a dependent Hibernate Entity without fetching the full entity?

查看:89
本文介绍了如何在不提取完整实体的情况下获取从属Hibernate实体的外键列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



安装程序是Hibernate 3中具有多对一关系的两个实体:

  @Entity 
class M {
private N n;
@ManyToOne(fetch = FetchType.LAZY)
public N getN(){return n; }
public void setN(N n){this.n = n; }
}

@实体
class N {
私人列表< M> ms = new ArrayList< M>();
@OneToMany(mappedBy =n)
public List< M> getMs(){return ms; }
public void setMs(List< M> ms){this.ms = ms; }
}

很简单。在我的应用程序中,我有一个 M s的列表,它们有一个 N 或者没有。该列表是 h:dataTable 的输入,它根据FK是否为空来显示不同的列内容。但是当我测试 m.getN()!= null 时,这会导致hibernate加载 N 。我怎样才能避免这种情况?



编辑:这实际上是我的错误,正如JBNizet在评论中指出的那样。至少对某人有用,并保持上面的布局,我将这个问题改为:如何在不提取完整实体的情况下获得依赖Hibernate实体的外键列值?正如Aaron Digulla所建议的那样。

编辑2 :结果显示新问题与此相同:

创建投影映射包含M或M的几个字段,例如您的查询可能会像

中的那样:

select new com.my .Maid(M,mnid)M m其中...


I'm struggling with a problem that seems way too easy:

Setup is two Entities with a Many-To-One Relationsship in Hibernate 3:

@Entity
class M {
  private N n;
  @ManyToOne(fetch = FetchType.LAZY)
  public N getN() { return n; }
  public void setN(N n) { this.n = n; }
}

@Entity
class N {
  private List<M> ms = new ArrayList<M>();
  @OneToMany(mappedBy="n")
  public List<M> getMs() { return ms; }
  public void setMs(List<M> ms) { this.ms = ms; }
}

Easy enough. In my application, I have a list of Ms that either have an N or don't. This list is the input for a h:dataTable that shows different column content depending on whether the FK is null or not. But when I test m.getN() != null this causes hibernate to load N. How can I avoid this?

Edit: this is actually an error of mine, as pointed out by JBNizet in the comments. To at least make this useful to someone and keep with the layout above, I've rephrased the question to "How do I get the foreign key column value of a dependent Hibernate Entity without fetching the full entity?" as suggested by Aaron Digulla.

Edit 2: Turns out the new question is a duplicate of this one: How can I prevent Hibernate fetching joined entities when I access only the foreign key id? - so, close vote?

解决方案

Create a projection mapping which contains M or several fields of M and e.g. id of N

Your query might liook sopething like

select new com.my.ProjectionObject(m, m.n.id) from M m where ...

这篇关于如何在不提取完整实体的情况下获取从属Hibernate实体的外键列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆