简体   繁体   中英

How do I get the foreign key column value of a dependent Hibernate Entity without fetching the full entity?

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 M s 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 eg id of N

Your query might liook sopething like

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

How do you expect Hibernate to tell you something it doesn't know? Without loading the entity, Hibernate has no way to know whether it (still) exists.

If you step outside the Hibernate "entity mapper" box, you can query the database directly and, for example, count the number of N s for your M .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM