Search code examples
javajpacomparecriteria

jpa criteria compare two strings in without considering spaces


I think that it is a basic question, but I'm struggling to get an answer.

The question is: using CriteriaBuilder and Predicate how can I compare strings without considering spaces in the middle. For example: "CH 525 kV AREIA 1077 PR". There isn't a "replace" function in CriteriaBuilder library.

cb.like(equipamento.get(EquipamentoBO_.txNomeLongo), "%" + dto.getTxNomeEquipamento().toUpperCase().replace(" ", "") + "%")

Thanks


Solution

  • There is a function method which should do the trick for you if you use REPLACE as the function to use:

    cb.like(
              cb.function("REPLACE"
                     , String.class
                     , equipamento.get(EquipamentoBO_.txNomeLongo)
                     , cb.literal(" ")
                     , cb.literal(""))
              , "%" + dto.getTxNomeEquipamento().toUpperCase().replace(" ", "") + "%"
           )