0

I'm new to the Criteria API and I'm trying to create a query that counts the entities of type B where A.someMethod(B) == true.

My entities:

@Entity
public class A {
    //Polymorphic function
    public boolean someMethod(B b) {
        // Processes b...
        return result;
    }
}

@Entity
public class B {
    // Some properties.
}

I don't know if it's possible to do that using JPA but I've sketched this:

CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
Root<B> countB = countQuery.from(B.class);
// a is already available.
countQuery.where(criteriaBuilder.isTrue(/*Expression that evaluates a.someMethod(B)*/));

The problem is I don't know how to create the Expression that goes with criteriaBuilder.isTrue(). I mean, I don't even know if I should be using criteriaBuilder.isTrue() to solve this.

So, could anyone help me with this? Currently I'm running a.someMethod() on all entities of type B after they are fetched from the DB but I'd like to restrict the result on the JPA layer itself.

Thanks!

Marcel
  • 5
  • 4

1 Answers1

1

You can't. the criteria api simply consists in dynamically building a query which is translated to SQL and executed by the database. The database doesn't know and care about your Java classes and methods.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks @JB Nizet, that makes perfect sense. It's what I was expecting but I had to check it somewhere other than the JEE docs. – Marcel Aug 21 '14 at 20:43