How to prevent Hibernate from nullifying relationship column during entity removal

Posted by Grzegorz on Stack Overflow See other posts from Stack Overflow or by Grzegorz
Published on 2010-05-17T10:13:59Z Indexed on 2010/05/17 10:30 UTC
Read the original article Hit count: 339

Filed under:

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)

© Stack Overflow or respective owner

Related posts about hibernate