Search code examples
javahibernatecriteria

Hibernate - Fetching data from joined table


please see the relation below:

Person {
    long idPerson;
    String name;

    @OneToMany( mappedBy="owner", cascade=CascadeType.ALL, fetch=FetchType.EAGER )
    List<Pet> pets;
}

@Inheritance( strategy=InheritanceType.JOINED )
Pet {
    long idPet;

    @ManyToOne
    @JoinColumn( name="ID_PERSON", nullable=false )
    Person owner;

    String name;
}

Cat extends Pet { }
Dog extends Pet { }
Dragon extends Pet { }

this is not the full code, but you get the idea ...

As you can see, the Strategy for InheritanceType is JOINED., so if I wanted to retrieve all the Person which has a Cat for example, my SQL would be like:

SELECT * FROM PERSON, PET, CAT
    WHERE PERSON.ID_PERSON=PET.ID_PERSON AND PET.ID_PET=CAT.ID_PET

How can I do it using Criterias? one "workaround" would be like this..:

Criteria criteria = session.createCriteria( Cat.class ).list();
// then manually create a List<Person> and add all the Cat.owner to that list

this would work fine for me if I didn't need to apply some Restrictions..

using criteria.createAlias("Pet", "pet") doesn't work, as it will retrieve all the Person regardless of it having a Cat or not. and .. criteria.createAlias("Cat", "cat") won't even compile as Person doesn't have Cat as a property.

In short, what I want to reach, is something equivalent to:

SELECT * FROM PERSON, PET, CAT
    WHERE PERSON.ID_PERSON=PET.ID_PERSON AND PET.ID_PET=CAT.ID_PET
        AND PERSON.something=...
        AND PET.something=...
        AND CAT.something=... ( and a lot more... )

well, this could have been a lot more easier if I used a TABLE_PER_CLASS Strategy, but in my real project, the JOINED one is the one which fits the best...

If possible, I would like to avoid using HQL for some .."complicated" reasons..

Thanks in advance!


Solution

  • Try this, this is how you can check for the class in inheritance.

    Criteria criteria = session.createCriteria( Person.class).createAlias("pets", "pet").add(Restrictions.eq("pet.class", Cat.class));