Extending hibernate entities with annotation

25,186

Yes, this one works without any problems. However you should have a look at the inheritance annotation.

What's the problem: You have a table "Abc" which contains field1,filed2; Then you have ExAbc which contains the fields of "Abc" and in adition field3. Now, if you think in terms of Databases, what should that system do with these two classes? Put them into a single table letting field3=null for all rows of type "Abc"? or put them into two different tables? or put the common fields in one table and create a second one for the additional filed3?

Each solution has its advantages and disadvantages as you can read in the link i posted, then its up to your situation to decide which is the best way.

(Default I think is the joined strategy, however I would not count on that being so for every database)

Share:
25,186
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin about 2 years

    i need to extend an entity, with the same characteristics without using abstract classes.

    can i code something like below?

    @Entity
    @Table(name="ABC")
    @SequenceGenerator(sequenceName="SEQ_ABC",name="idGenerator",allocationSize=1)
    public class Abc {
    .. // define members
    }
    
    @Entity
    @Table(name="EX_ABC")
    public class ExAbc extends Abs {
    .. // define extras..
    }
    

    thx in advance

  • Admin
    Admin over 13 years
    Thx for the answer Hons, my business rules fit to @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS), but when i fetch records, i get both parent and child records (UNION ALL), how can i fetch the particular parent or child record. thx in advance again
  • Hons
    Hons over 13 years
    Sorry, I'm not sure what you mean. You do a SELECT on the EX_ABC and then you receive entities of both tables?
  • Martin
    Martin about 11 years
    Yes, this is what happens.. don't know how to avoid that, me too. See forum.hibernate.org/viewtopic.php?f=1&t=958277
  • Hons
    Hons almost 11 years
    I guess you could fix that by adding to your select a condition that one of the fields you add in the EX_ABC is different from NULL. I would need to try that out in an example, but it should work
  • Victor
    Victor almost 6 years
    @Hons just a note to what you said, default strategy is InheritanceType.SINGLE_TABLE, as per documentation you already mentioned