Friday, 12 February 2010

OneToMany Mapping

Sounds trivial, but it recently came to my attention that the OneToMany mappings in our app looked like this ...
@OneToMany(targetEntity = ChildItem.class, mappedBy = "parentId")
@NotFound(action = NotFoundAction.IGNORE)
public List<ChildItem> getChildItems() {
return childItems;
}
This worked (for a while) but it makes the assumption that the foreign key in the 'many' table is mapped to the primary key in the 'one' table. Of course, this caused us no end of grief when we discovered that the parent ID is non-unique and changed the table to include a real ID.

In fact, a more standard approach looks like this:
@OneToMany
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
@NotFound(action = NotFoundAction.IGNORE)
public List<ChildItem> getChildItems() {
return childItems;
}
The JoinColumn annotation is basically saying "join these tables by mapping the PARENT_ID in the child items table to PARENT_ID in the parent items table".

No comments: