Filter entities by a specific subclass type using Criteria


#1

Hello,

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(Restrictions.in("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?

@MappedSuperclass 
@DiscriminatorColumn
public class A {
Long id;
}

@Entity
@Table(name="table1")
@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
}

#2

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);
q.select(root)
.where(cb.notEqual(root.type(), B.class));