How to override the collection element type in subclass in hibernate?
For example, a Tiger is a Cat, but Tiger won't have any Cat child:
@Entity
class Cat {
@OneToMany(targetEntity=Cat.class)
Set<Cat> getChildren() { ... }
}
And the Tiger:
@Entity
class Tiger extends Cat {
@OneToMany(ta开发者_运维百科rgetEntity=Tiger.class)
Set<Cat> getChildren() { ... }
}
The problem is, Hibernate won't allow such definition, as error:
Repeated column in mapping for entity: com.bee32.plover.orm.Tiger column: parent (should be mapped with insert="false" update="false")
Any idea?
We do it by providing a XML file (root element: ...), but why do you need it in the first place?
Normally, you would restrict the Tiger class to only accept children of the same class, so getChildren()
would return a set of tigers.
In the database you'd have a discriminator defining the entity class of the dataset anyways. So if you assign a dataset with discriminator "CAT" (or similar) as the child of a "TIGER" you'd get an exception when loading the association anyways (since the entity would be of class Cat
and can't be cast to Tiger
).
精彩评论