使用元模型区分大小写的JPA 2 Criteria API

时间:2013-01-15 08:47:07

标签: java hibernate jpa criteria-api

我有以下代码行来使用Hibernate 4 API

基于like语句获取结果
Predicate predicate = cb.like(emp.get(EmployeeDetail_.empName),
                empName+"%");

生成的sql语句是

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

如何修改我的Java代码以使EMPLOYEE_NAME小写?生成的sql输出应该类似于以下

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

获取结果的完整代码

   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 个答案:

答案 0 :(得分:3)

使用CriteriaBuilder#lower()

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