I am trying to setup a 1to0..1 (zero or one) relationship, but am running into issues.
Now my assumption is to use the @OneToMany, and not @OneToOne.
Basically I want my “child” table to hold the foreign key to the “parent” (I use child and parent very loosely). I never need to load “children” standalone
This is the basic table structure I want to achieve
ITEM {
ID
RELATED_ITEM_ID
}
INVOICE {
ID
}
CATALOGUE {
ID
}
Reprsented as Java classes like the following
class Item {
...
}
class Invoice {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
class Catalogue {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
The above code, if I only have Invoice or Catalogue registered in hibernate will create the tables as I want, and work perfectly. However, as soon as I have both Invoice and Catalogue registered, hibernate throws me the error
org.hibernate.MappingException: Duplicate property mapping of _itemsBackref found in package.name.Item
I sort of ended up cheating to get this to work how I want. I dont ideally want a hierachy like that, but I need to get this working, and I feel this is a compromise with working around hibernate.
Reprsented as Java classes like the following