开发者

Hibernate mapping in 2 different tables of Java entities with inheritance between them

I'm working on a Hibernate inheritance mapping problem开发者_运维技巧 for which I cannot seem to find an answer.

I have 2 have classes:

Child extends Parent

and I have mapped them both as if they were 2 different models, simply using 2 hbm files, with no inheritance, just a <class> element. This means that the hbm for the child does repeat the fields that are defined in the hbm for the parent.

The reason for this is that I wanted them to be completely independent, because the child has different constraints than the parent, so they're mapped to 2 different tables as 2 different models, they just happen to be child parent in java.

The problem now is that the queries do not behave independently - Hibernate knows that the 2 java classes have an inheritance relation between them so when I try to retrieve instances of Child, but Hibernate finds 2 implementors for it and returns results from both tables.

I'm aware that this is kind of a weird usage case, but if anyone has any suggestion that doesn't involve just removing the inheritance between Child and Parent (which I'm considering if I cannot find another solution), I would try something else first.


Let me precede this answer with a warning that

  • It sounds like there might be a better way than inheritance if you're trying to do these queries
  • Even if you fix these queries you're likely to encounter other issues

That being said you shouldn't differentiate query results on inheritance like this. This is not the normal usage. Typically query results should be based on fields in the table. I would suggest creating a boolean field isChild which the child constructor sets to true and the parent constructor sets to false. You can then just query for all objects based on that field to get all parents or all children.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜