Hi i am using Java 1.6 with hibernate and spring. I am having problems with hibernate models using inheritance mapping of type @Inheritance(strategy=InheritanceType.JOINED), or table per subclass.
Scenario:
- we have 3 tables each mapped to a hibernate model
- each table shares the same single column primary key
- the java models extend each other of the form
A extends B, andB extends C - each table is normalized ie, subclasses share the same pk and add more properties
We are trying to use annotations only to be able to load any of the classes listed above. Ie. we want to be able to load A only (which will load from B and C and populate A with all the properties) , we also want to be able to load B (which would only load C as well) and C by itself.
What i have done:
- added annotation
@Inheritance(strategy=InheritanceType.JOINED)toC - removed instance variable, setter and getter for the primary key column from
AandB - removed
equals()andhashCode()methods fromAandBbecause it is inCand it's implementation is the same (checks only the primary key column)
Observed behaviour:
if i define B and C only in spring.hibernate.xml then:
- i can load
Band it behaves as expected, it loads values ofCas well. Other database operations also work correctly, for eg. save, saves to tablesBandC. - if i try to load
C, the command fails with the following error (note that i replaced the concrete class names, withA,B,andCrespectively from my example:
No unique bean of type [C] is defined: expected single bean but found 2: B,C
if i define A and C only, then the behaviour is:
- i can load
Aand everything is as expected (as above forB) - i can't load
C, i get the same error as above withAandCthis time
if i define A, B and C in spring.hibernate.xml i get:
- when it try to load
Bi get the exception:
No unique bean of type [B] is defined: expected single bean but found 2: B,A
- when i try to load
Athen it works - when i try to load
Ci get:
No unique bean of type [C] is defined: expected single bean but found 2: B,C,A
I would prefer to handle this 3 layer inheritance using annotations only, but i'm open to adding custom xmls for each model if that's the only way to do it. Supporting this scenario is more important that avoiding having model.hbm.xml files.
Any help would be much appreciated as examples and documentation has been hard to find online or is very simplified.