Hello,
Let A be a container class with a Set of objects of class B, with bidirectional mapping.
B holds a reference to an object of class C.
B has a composite primary key composed of its two references to the A and C objects.
Here are my corresponding simplified annotated classes :
Code:
@Entity
public class A implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.AUTO) private long id;
@OneToMany(mappedBy="A", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private Set<B> myBs = new HashSet<B>();
}
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@IdClass(BPrimaryKey.class)
public class B implements Serializable {
@Id @ManyToOne private A myA;
@Id @ManyToOne private C myC;
}
@Embeddable
public class BPrimaryKey implements Serializable {
@ManyToOne private A myA;
@ManyToOne private C myC;
}
@Entity
public class C implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.AUTO) private long id;
}
I create object 'a' and 'c' of classes A and C, and an object b of class B which references a and c. a also has b in its myBs set. I saveOrUpdate a and c and everything gets correctly created and linked in the database (thanks to cascade).
In an other session, the next step loads 'a' back from the database and the saveOrUpdate it. Ok.
Now I create a subB subclass like this :
Code:
@Entity
public class subB extends B { /*data omitted*/ }
I run the same test using a subB instance instead of a B : creation and association to 'a' and 'c', then saving. Fine. But the next step (load 'a' and simply save it) fails with a "Duplicate entry" error message while the SQL trace shows that Hibernate tries to insert the subB instance again, with the same composite key ('a' and 'c' ids).
Using a TABLE_PER_CLASS or a SINGLE_TABLE inheritance strategy does not solve the problem.
The database creation script are very similar for B and subB, both declaring a "primary key (A_id, C_id)". But it works well with the super class (B), but fails with inherited classes (subB).
Using Hibernate 3.2.3, annotations V3.3.0 and MySQL 4.1.12.
Could you tell me what is wrong in this example ? I'm new to hibernate, do not hesitate to ask if you need more information.
Thanks in advance,
Gilles