tags:

views:

27

answers:

1

I have two entities, A and B. I need to easily retrieve entities A, joined with entities B on the condition of equal values of some column (some column from A equal to some column in B). Those columns are not primary or foreign keys, they contain same business data. I just need to have access from each instance of A to the collection of B's with the same value of this column. So I model it like this:

class A {
  @OneToMany
  @JoinColumn(name="column_in_B", referencedColumnName="column_in_A")
  Collection<B> bs;

This way, I can run queries like "select A join fetch a.bs b where b...." (Actually, the real relationship here is many-to-many. But when I use @ManyToMany, Hibernate forces me to use join table, which doesnt exist here. So I have to use @OneToMany as workaround). So far so good. The main problem is: whenever I delete an instance of A, hibernate calls "Update B set column_in_B = null", becuase it thinks the column_in_B is foreign key pointing at primary key in A (and because row in A is deleted, it tries to clean the foreign key in B). BUT the column_in_B IS NOT a foreign key, and can't be modified, because it causes data lost (and this column is NOT NULL anyway in my case, causing data integerity exception to be thrown).

Plese help me with this. How to model such relationships with Hibernate? (I would call it "virtual relationships", or "secondary relationships" or so: as they are not based on foreign keys, they are just some shortcuts which allows for retrieving related objects and quering for them with HQL)

A: 

Based on the Hibernate book, it seems that this is only possible with XML mapping, not with annotations:

Unfortunately, at the time of writing, Hibernate Annotations doesn’t support arbitrary join conditions expressed with formulas. The grouping of properties under a reference name also wasn’t possible.

Péter Török
But, if I used XML, would I be able to model such relationship, that when I delete an entity A, Hibernate will not nullify the relationship column in table B?
Grzegorz
@Grzegorz, I have never done this myself, so can't guarantee anything. But from what I read in the book, it seems to be possible. Google "Hibernate arbitrary join conditions with formulas" if you are interested in experimenting with this.
Péter Török
From what I've just read, it looks like it could do the trick. Unfortunately, it seems quite heavy weight and complicated, for such simple requirement... I just want to tell hibernate "don't set this column to null", withouth rewriting all my mappings :(
Grzegorz