简体   繁体   中英

Using JPA criteria API to select with pattern

My code snippet:

criteriaQuery.select(root);
Predicate ctfPredicate;

if (deptPattern.contains("%") || deptPattern.contains("_")) {
    deptPattern = deptPattern.replaceAll("%", "^%").replaceAll("_", "^_");
}
System.out.println("case sensitive  " +deptPattern);
ctfPredicate = criteriaBuilder.like((Expression)root.get("name"), "%" + deptPattern + "%", '^');            

criteriaQuery.where(criteriaBuilder.and(ctfPredicate));

TypedQuery<Object> typedQuery = entitymanager.createQuery(criteriaQuery);
List<Object> resultlist = typedQuery.getResultList();
printResult(resultlist);

The resultList does not return anything, whereas db has 2 entries with dname Sales. Query getting printed : select department0_.deptno as deptno0_, department0_.loc as loc0_, department0_.dname as dname0_ from mydept department0_ where department0_.dname like ? escape ?

Database used is Oracle and JPA2.0 vendor is EclipseLink

The db had entries with name as Sales, without %. And the input pattern was given as 'Sales%'. I changed it to 'Sales', since the code was adding '%' to the input. And the result list returned both the entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM