Question

How could I compare an uppercase with JPA QueryBuilder?

SQL:

SELECT * FROM PERSON WHERE UPPER(name) = ?

And the I add: searchName.toUpperCase()

Was it helpful?

Solution

Here is a solution:

public List<Person> getPersonsByUpperName(String searchName) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Person> cq = cb.createQuery(Person.class);
    Root<Person> person= cq.from(Person.class);

    Path<String> name = person.get("name"); //table column

    cq.select(person);
    cq.where(cb.equal(cb.upper(name), cb.parameter(String.class, "nameUpper")));

    TypedQuery<Person> q = em.createQuery(cq);
    q.setParameter("nameUpper", searchName.toUpperCase());;

    return q.getResultList();
}

This works for any input string (Dimitri, dimitri, etc.) as uppercase conversion is performed inside the method:

  • table column: cb.upper(name)
  • query parameter: searchName.toUpperCase()

I hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top