23

How I can cast Integer to a String for Criteria Query?

i.e.:

Predicate predicate = criteriaBuilder.like((Expression) root.get(filterKey),
                    "%" + filterValue + "%");

I wan to create filter for dataTable component.... and i.e. for ID value I want to get filter like this:

If I type "1" I will get all items with ID containing "1" (223122 ID will be still correct)

double-beep
  • 5,031
  • 17
  • 33
  • 41
Marcin Petrów
  • 1,447
  • 5
  • 24
  • 39

3 Answers3

22

I have not used this myself, but this other question:

Using JPA 2.0 Criteria API and cast causes generated JPQL to fail in Hibernate

Suggests using .as(String.class) after root.get(filterKey) to accomplish what you want.

If you're using Hibernate, be aware of reported bugs

Community
  • 1
  • 1
Doug Moscrop
  • 4,479
  • 3
  • 26
  • 46
15

Try it

Predicate predicate = criteriaBuilder.like(root.get(filterKey).as(String.class),
                    "%" + filterValue + "%");
Gianluca Musa
  • 755
  • 7
  • 22
4

This solved problem for me:

Expression<String> filterKeyExp = root.get(filterKey).as(String.class);
filterKeyExp = criteriaBuilder.lower(filterKeyExp);

Predicate predicate = criteriaBuilder.like(filterKeyExp ,"%" + filterValue.trim().toLowerCase() + "%");
toskebre
  • 385
  • 2
  • 7
  • 18