JPA/Criteria API - Like & equal problem

前端 未结 4 807
南笙
南笙 2020-12-08 00:27

I\'m trying to use Criteria API in my new project:

public List findEmps(String name) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
             


        
相关标签:
4条回答
  • 2020-12-08 00:41

    Better: predicate (not ParameterExpression), like this :

    List<Predicate> predicates = new ArrayList<Predicate>();
    if(reference!=null){
        Predicate condition = builder.like(root.<String>get("reference"),"%"+reference+"%");
        predicates.add(condition);
    }
    
    0 讨论(0)
  • 2020-12-08 00:47

    Use :

    personCriteriaQuery.where(criteriaBuilder.like(
    criteriaBuilder.upper(personRoot.get(Person_.description)), 
    "%"+filter.getDescription().toUpperCase()+"%")); 
    
    0 讨论(0)
  • 2020-12-08 00:49

    I tried all the proposals and although it did not give an error, it did not recover anything if I did not put all the expected text, in the end what was proposed by user3077341 worked for me but with the variant that I use '%' instead of "%", the like worked perfect.

    List<Predicate> predicates = new ArrayList<Predicate>();
    if(reference!=null){
        Predicate condition = builder.like(root.<String>get("reference"),'%'+reference+'%');
        predicates.add(condition);
    }
    
    0 讨论(0)
  • 2020-12-08 01:03

    Perhaps you need

    criteria.add(cb.like(emp.<String>get("name"), p));
    

    because first argument of like() is Expression<String>, not Expression<?> as in equal().

    Another approach is to enable generation of the static metamodel (see docs of your JPA implementation) and use typesafe Criteria API:

    criteria.add(cb.like(emp.get(Employee_.name), p));
    

    (Note that you can't get static metamodel from em.getMetamodel(), you need to generate it by external tools).

    0 讨论(0)
提交回复
热议问题