我正在使用Hibernate 4,我想在我的DAO类中使用以下代码 从我的表中获得结果
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,
"employeeNumber");
Predicate predicate = cb.like(emp.get(Employee_.employeeNumber),
pexp);
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<Employee> q = entityManager.createQuery(c);
if (employeeNumber != null) {
q.setParameter("employeeNumber", employeeNumber);
data.setResult(q.getResultList());
当页面运行时,从日志中我可以看到sql为
select employeede0_.EMPLOYEE_NUMBER as EMPLOYEE1_0_ from EMPLOYEES employeede0_
where employeede0_.EMPLOYEE_NUMBER like ?
因此,我无法看到任何结果。理想情况下,我希望有一个像
这样的查询select employeede0_.EMPLOYEE_NUMBER as EMPLOYEE1_0_ from EMPLOYEES employeede0_
where employeede0_.EMPLOYEE_NUMBER like '123%'
我怎样才能做到这一点?
答案 0 :(得分:2)
您希望最终执行
Predicate predicate = cb.like("employeeNumber", "123%");
所以包括百分比。
答案 1 :(得分:1)
这应该适合你:
criteria.add ( Restrictions.like ("employeeNumber", "123%" ) );