user959690
user959690

Reputation: 620

How do you query by Hibernate polymorphic criteria properties

Assume

@Entity 
Class Animals { }

@Entity
@Inheritance( stragegy = InheritanceType.JOINED)
class Dogs extends Animals {
    private String furType;
}

@Entity
@Inheritance( stragegy = InheritanceType.JOINED)
class Cat extends Animals {
    private String furType;
}

All entities are real classes in my database and I don't have the option of redesigning our database.

How can I used a DetactedCriteria to create a disjunction query that says give me all "Animals" where furType= 'loud' for dogs OR furType= 'soft' for cats? Sorry I didn't design the class hierarchy so I'm not responsible for the fact that the property names are the same and I can't redesign it because there are other subclasses who's tables don't contain "furType".

Upvotes: 2

Views: 996

Answers (1)

Piotr Nowicki
Piotr Nowicki

Reputation: 18224

In JPA 2.0 you can use the TYPE() construct to do this job. Something like this (not checked) should work:

SELECT a 
  FROM Animals a 
  WHERE (TYPE(a) = Dogs AND a.furType = 'loud') OR 
        (TYPE(a) = Cat AND a.furType = 'soft')

Upvotes: 2

Related Questions