9

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?

Community
  • 1
  • 1
mabi
  • 5,141
  • 1
  • 34
  • 70
  • 1
    It shouldn't. Make sure you don't call any method on the N returned by `m.getN()` – JB Nizet Aug 02 '12 at 11:40
  • @JBNizet Ew, you're right. The actual query asks for another Entity that's connected OneToOne to M. Reading skills--. Now I feel stupid. – mabi Aug 02 '12 at 12:13

2 Answers2

1

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 ...

Piotr Gwiazda
  • 11,796
  • 12
  • 53
  • 87
-1

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 Ns for your M.

Aaron Digulla
  • 297,790
  • 101
  • 558
  • 777
  • Default hibernate creates a FK on M. If M were a normal hashmap of columns, i'd check m.get("n_id") != null. I should probably edit the question to include both PKs, so it's more obvious. – mabi Aug 02 '12 at 11:59
  • 1
    That's a different question. What you want to know is "How do I get the ID which Hibernate will use when I call getN()?" – Aaron Digulla Aug 02 '12 at 12:06