I am using Hibernate Core 3.2.5.GA and Hibernate Annotations 3.3.0.GA.
I am having trouble with composite primary/foreign keys and sequence of classes with bidirectional one-to-many relationship between them. I am getting strange annotation exception with annotations that seem to be perfectly ok.
My conclusion is that the name of classes need to be in alphabetical order, otherwise misleading exception about the number of columns is thrown.
Consider the following classes A, B and C:
Code:
@Entity
public class A {
@Id
private int id;
@OneToMany(mappedBy="parent")
List<B> children;
}
@Entity
@IdClass(BId.class)
public class B {
@Id
private A parent;
@Id
private int sequenceNumber;
@OneToMany(mappedBy="parent")
List<C> children;
}
@Entity
@IdClass(CId.class)
public class C {
@Id
private B parent;
@Id
private int sequenceNumber;
}
Here are also the idclasses for composite keys in classes B and C:
Code:
@Embeddable
public class BId implements Serializable {
@ManyToOne
@JoinColumn(name="aId",nullable=false)
private A parent;
private int sequenceNumber;
}
@Embeddable
public class CId implements Serializable {
@ManyToOne
@JoinColumns({
@JoinColumn(name="aId",nullable=false),
@JoinColumn(name="bSequenceNumber",nullable=false)
})
private B parent;
private int sequenceNumber;
}
This mapping works fine. But if you change classes B and C with each other (rename B to C, and C to B) so that the sequence of classes is A --> C --> B, you'll get an AnnotationException which makes no sense:
Code:
Caused by: org.hibernate.AnnotationException: A Foreign key refering C from B has the wrong number of column. should be 1
The reason for this seems to be the alphabetical order of the class names! Sequence A --> B --> C is fine but A --> C --> B is not.
If you use @Table to define the database table names, it is the table names that need to be in alphabetical order.
The same error can be also produced with @SecondaryTable in class/table that has composite PK. This case is more difficult since you cannot get rid of the exception, no matter how you name your classes or tables. I believe this is the same bug that appears in the comments of
ANN-509 .