@OneToMany and composite primary keys?
- by Kris Pruden
Hi,
I'm using Hibernate with annotations (in spring), and I have an object which has an ordered, many-to-one relationship which a child object which has a composite primary key, one component of which is a foreign key back to the id of the parent object.
The structure looks something like this:
+=============+ +================+
| ParentObj | | ObjectChild |
+-------------+ 1 0..* +----------------+
| id (pk) |-----------------| parentId |
| ... | | name |
+=============+ | pos |
| ... |
+================+
I've tried a variety of combinations of annotations, none of which seem to work. This is the closest I've been able to come up with:
@Entity
public class ParentObject {
@Column(nullable=false, updatable=false)
private String id;
@OneToMany(mappedBy="object", fetch=FetchType.EAGER)
@IndexColumn(name = "pos", base=0)
private List<ObjectChild> attrs;
...
}
@Entity
public class ChildObject {
@Embeddable
public static class Pk implements Serializable {
@Column(nullable=false, updatable=false)
private String objectId;
@Column(nullable=false, updatable=false)
private String name;
@Column(nullable=false, updatable=false)
private int pos;
...
}
@EmbeddedId
private Pk pk;
@ManyToOne
@JoinColumn(name="parentId")
private ParentObject parent;
...
}
I arrived at this after a long bout of experimentation in which most of my other attempts yielded entities which hibernate couldn't even load for various reasons.
The error I get when I try to read one of these objects (they seem to save OK), I get an error of this form:
org.hibernate.exception.SQLGrammarException: could not initialize a collection: ...
And the root cause is this:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'attrs0_.id' in 'field list'
I'm sure I'm missing something simple, but the documentation is not clear on this matter, and I haven't been able to find any examples of this anywhere else.
Thanks!