Search code examples
javahibernateoophqlobject-oriented-database

Hibernate, get child object from abstract parent


I am getting a parent abstract object from hibernate. What is the best way to get true child object?

I think this is not a correct way to do it:

Long parentId=parent.getId();
Child child=childMgr.getInstance().getById(parentId);

Solution

  • Your Child should be already declared in your Parent object class:

    public class parent{
        private Child child ;
    //setter getter
    }
    

    then in your parent hbm (varies if using annotation) you map it:

    <one-to-one cascade="none" name="child" not-null="true"
            class="com.example.child" 
            column="FOREIGN_KEY" />
    

    Then once you have the parent you can just call:

    Child child = parent.getChild();
    

    This only applies if you have one to one relationship, varies for one to many, will need to set as list.