Due to various ridiculous legacy constraints, I have an odd requirement. I have to manually manage a many-to-many relationship and also manually assign the primary key of both sides of the relationship. I thought I had this set up properly, but I'm getting cascade problems.
I have two entities - E1 and E2. There is a many-to-many relationship between these two. I have to apply some attributes to the relationship between these two entities, though, so I'm manually managing the join table between them. Some code to illustrate:
Code:
public class E1 {
Integer id;
String name;
Set<E1E2> joins;
@OneToMany( mappedBy="e1" cascade = CascadeType.ALL )
public Set<E1E2> getJoins() {
return joins;
}
...
}
public class E1E2 {
Integer id;
E1 e1;
E2 e2;
String someOtherAttribute;
@ManyToOne()
@JoinColumn( name = "E1id" )
public E1 getE1() {
return e1;
}
@ManyToOne()
@JoinColumn( name = "E2id" )
public E2 getE2() {
return e2;
}
...
}
public class E2 {
Integer id;
String name;
...
}
Because of some other requirements, I also have to set the ids of both E1 and E2. So, my code would end up looking something like this:
Code:
E1 entity1 = new E1();
entity1.setId(123);
E2 entity2 = new E2();
entity2.setId(456);
E1E2 join = new E1E2();
join.setE1(entity1);
join.setE2(entity2);
entity1.getJoins().add(join);
getHibernateTemplate().save(entity1);
I'd like the save of entity1 to cascade down through E1E2 and E2, but this isn't working right. The SQL generated ends up like this (paraphrased of course):
insert into E1(id) values (123)
select * from E2 where id=456 -- returns null because E2 doesn't exist yet
insert into E1E2 (E1id, E2id) values (123, null)
This of course triggers an exception because I don't allow nulls in the FK field.
I realize this is somewhat non-standard, but I don't know why Hibernate is replacing the E2 id I set with null.