JPA 2 Criteria API using metamodel case sensitive condition

旧时模样 提交于 2019-12-11 08:17:02

问题


I have the following line of code to get the results based on like statement using Hibernate 4 API

Predicate predicate = cb.like(emp.get(EmployeeDetail_.empName),
                empName+"%");

The generated sql statement is

 select employeede0_.EMPLOYEE_NAME as EMPLOYEE1_0_ from EMPLOYEES employeede0_ 
        where employeede0_.EMPLOYEE_NAME like 'smith%'

How can I modify my java code to have EMPLOYEE_NAME in lower case? The generated sql output should be like the following

select employeede0_.EMPLOYEE_NAME as EMPLOYEE1_0_ from EMPLOYEES employeede0_ 
    where lower(employeede0_.EMPLOYEE_NAME) like lower('smith%')

Complete code for getting results

   CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
        Root<Employee> emp = c.from(Employee.class);
        c.select(emp);
        List<Predicate> criteria = new ArrayList<Predicate>();
        ParameterExpression<String> pexp = cb.parameter(String.class,
                "empName");
        Predicate predicate = cb.like(emp.get(Employee_.empName),
                empName+"%");
        criteria.add(predicate);

        if (criteria.size() == 1) {
            c.where(criteria.get(0));
        } else if (criteria.size() > 1) {
            c.where(cb.and(criteria.toArray(new Predicate[0])));
        }
        TypedQuery<EmployeeDetail> q = entityManager.createQuery(c);
        data.setResult(q.getResultList());

回答1:


Use CriteriaBuilder#lower():

Predicate predicate = cb.like(cb.lower(emp.get(EmployeeDetail_.empName)),
            empName.toLowerCase() + "%");


来源:https://stackoverflow.com/questions/14333997/jpa-2-criteria-api-using-metamodel-case-sensitive-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!