views:

35

answers:

0

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, and B 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) to C
  • removed instance variable, setter and getter for the primary key column from A and B
  • removed equals() and hashCode() methods from A and B because it is in C and 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 B and it behaves as expected, it loads values of C as well. Other database operations also work correctly, for eg. save, saves to tables B and C.
  • if i try to load C, the command fails with the following error (note that i replaced the concrete class names, with A,B,and C respectively 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 A and everything is as expected (as above for B)
  • i can't load C, i get the same error as above with A and C this time

if i define A, B and C in spring.hibernate.xml i get:

  • when it try to load B i get the exception:

No unique bean of type [B] is defined: expected single bean but found 2: B,A

  • when i try to load A then it works
  • when i try to load C i 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.