creating a Criteria Query using java predicate

36 views Asked by At

I'm trying to create a generified get method for my DAO implementation that takes a predicate of that generic type and returns an object that makes the respective predicate.test() return true

is there a way to create a valid Criteria Query that can be later passed as argument to the where() function, with a predicate defined on an Entity class ?

for example :

Class User {
String name;
}


var predicate = new Predicate<User> {
public boolean test(User user) {return user.name.equals(...);}

other methods...
}


public T get(Predicate<T> predicate, Class<?> outputClass) {

CriteriaQuery cq = entityManager.getCriteriaBuilder.createQuery();
Root<T> root = cq.from(someClass);
cq.select(root).where(predicet) // I need to somehow pipe the predicate into this method


blah blah blah
}

if there was a way to get the entity representing the root object and pass that into the test method that would have been fine as well

for example I need to get the user with a specific name (NAME)

the valid criteria query :

var builder0 = session.getCriteriaBuilder();
var cQuery0 = builder0.createQuery(User.class);
var root0 = cQuery0.from(User.class);
cQuery0.select(root0).where(builder0.equal(root0.get("name"), "NAME"));

but I'd like to implement that using a predicate with the following test method...

public boolean test(User user) {
return user.name.equals("NAME");
}
0

There are 0 answers