Comrades,
My database table has a parentId field that maps to the (primary key) itemId field of the
same table. This is a one-way relationship. Rows don't need a link to the child, and neither do the Entities they map to.
I've found examples where a parent column maps to a different table, but I've never found one for the same table, so I decided to just try it. But my code didn't work, and now I'm stumped.
Here's what I tried, that didn't work. First, in the database, I mapped a "foreign" key to the same table (in MySQL):
Code:
ALTER TABLE `item` ADD CONSTRAINT `item_item`
FOREIGN KEY (`parentId`) REFERENCES `item` (`itemId`);
My Entity looks like this:
Code:
@Entity
@Table(name = "item")
public class Item implements java.io.Serializable {
private Long itemId;
private Item parentItem;
public Item() { }
@Id
@Column(name = "itemId", unique = true, nullable = false)
public Long getItemId() {
return this.itemId;
}
@ManyToOne(targetEntity = Item.class)
@JoinColumn(name = "itemId", nullable = true, updatable = false, insertable = false)
public Item getParentItem() {
return this.parentItem;
}
public void setParentItem(Item parentItem) {
this.parentItem = parentItem;
}
}
When I run my test case, with five rows in the "item" table, it doesn't map the values that are in the database. Instead, for four of the items, it acts as if the parentId were equal to the itemId, and leaves the fifth parent null.
Here's the actual data from the table:
Code:
+--------+----------+
| itemId | parentId |
+--------+----------+
| 1 | NULL |
| 2 | 1 |
| 3 | 2 |
| 4 | NULL |
| 5 | 3 |
+--------+----------+
But it behaves as if the data were this:
Code:
+--------+----------+
| itemId | parentId |
+--------+----------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | NULL |
+--------+----------+
Incidentally, my @JoinColumn annotation originally looked like this:
Code:
@JoinColumn(name = "itemId", nullable = true)
but I got this exception:
org.hibernate.MappingException: Repeated column in mapping for entity: com.evryx.db.Item column: itemId (should be mapped with insert="false" update="false")
I was able to make it run by adding
Code:
updatable = false, insertable = false
to the JoinColumn annotation, but these values are wrong. I will need to insert and update these values when I get it working.
Is there a way to do this with Hibernate?