JPA 2 Criteria API case insensitive condition with

2019-05-02 06:34发布

问题:

How to create Case-insensitive Criteria Query without metamodel usage?

I'm trying to do something like this:

   CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Resident> criteria = builder.createQuery(Resident.class);
    Root<Resident> personRoot = criteria.from(Resident.class);

    criteria.where(builder.and(
            builder.equal(builder.upper(personRoot.get("firstName")), filter.getFirstName())),  //ERROR
            builder.equal(personRoot.get("lastName"), filter.getLastName()));

But it produce error:

method upper in interface javax.persistence.criteria.CriteriaBuilder cannot be applied to given types; [ERROR] required: javax.persistence.criteria.Expression [ERROR] found: javax.persistence.criteria.Path

回答1:

try

Expression<String>  firstName = personRoot.get("firstName");

criteria.where(builder.and(
            builder.equal(builder.upper(firstName ), filter.getFirstName())),   
            builder.equal(personRoot.get("lastName"), filter.getLastName()));

seems like it method upper has some problems with accepting path



回答2:

This should compile:

...builder.upper(personRoot.<String>get("firstName"))...