1

How to make a concatenation of 3 fields? I want to make a search by input string. Expressions like

%firstName%LastName%Patr%

with different orders possible %LastName%Patr%firstName% etc

How can i do that?

My code do search only for one field, but i need for 3 at the same time

  @Override
    public List<Teacher> searchByString(String str) {

        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Teacher> criteriaQuery = criteriaBuilder.createQuery(Teacher.class);
        Root<Teacher> teacherRoot = criteriaQuery.from(Teacher.class);

        Expression concatForOtch = criteriaBuilder.concat(teacherRoot.get("otch"),"%");

        Expression concatForName = criteriaBuilder.concat(teacherRoot.get("name"),"%");

        Expression concatForFam = criteriaBuilder.concat(teacherRoot.get("fam"),"%");

        Expression almostFinalExpression = criteriaBuilder.concat(concatForName,concatForOtch);

        Expression finalExpression = criteriaBuilder.concat(concatForFam,almostFinalExpression);

        Expression fullExpression = criteriaBuilder.concat("%", finalExpression);

        Predicate pr = criteriaBuilder.like(fullExpression,"%" + str + "%");

        criteriaQuery.where(pr);

        return em.createQuery(criteriaQuery).getResultList();

    }
jarlh
  • 42,561
  • 8
  • 45
  • 63
Vytsalo
  • 670
  • 3
  • 9
  • 19

1 Answers1

1

You can add field annotated with @Formula to the entity

@Formula("concat(fam, name, otch)")
private String fullName;

where fam, name, otch are columns names.

And use it this way

Predicate predicate  = criteriaBuilder.like(teacherRoot.get("fullName"),"%" + str + "%");
Oleksii Valuiskyi
  • 2,691
  • 1
  • 8
  • 22
  • 1
    I would not want to create a new field just for search – Vytsalo Oct 22 '19 at 11:10
  • Expression concatForOtch = criteriaBuilder.concat(teacherRoot.get("otch"),"%"); Why do you concatenate each column with a "%"? Try to replace "%" with a whitespace, except this one Predicate pr = criteriaBuilder.like(fullExpression,"%" + str + "%"); – Oleksii Valuiskyi Oct 22 '19 at 11:56