Filter entities by a specific subclass type using Criteria


I have the classes listed below. I need to get Class B from the database and only class B matched on some property.

When I try :

DetachedCriteria criteria = DetachedCriteria.forClass(B.class);

it returns everything that matches class B and class C.

How can I add a restriction to map it based on the class also. I tried:

criteria.add("class", B.class));

but class is not defined as a valid property. Do you have any suggestions to fix this without looping through the list checking if it is an instance of B?

public class A {
Long id;

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class B extends A{
int x;
int y;

public class C extends B {
// just a few methods and no database calls

The legacy Hibernate Criteria is deprecated and might be removed in a future release.

You should use the JPA Criteria API instead, and you can achieve your goal like this:

CriteriaQuery<B> q = cb.createQuery(B.class);
Root<B> root = q.from(B.class);
.where(cb.notEqual(root.type(), B.class));