Java – JPA CriteriaBuilder and Substring

criteria-apieclipselinkjavajpajpa-2.0

I have a CriteriaBuilder where I am trying to get characters starting from 0 to 10. However I am not able to get the desired output.

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Emp> cq = cb.createQuery(Emp.class);
    Root<Emp> c = cq.from(Emp.class);
    cb.substring(c.<String>get("projDesc"), 0, 10);
    cq.orderBy(cb.desc(c.get("salary")));
    Query query = em.createQuery(cq);
    .....

What could be the reason for this?

Best Answer

From the javadoc

Create an expression for substring extraction. Extracts a substring of given length starting at the specified position. First position is 1.

Try doing cb.substring(c.<String>get("projDesc"), 1, 10);


I think you're forgetting to select the Expression<E>

Try cq.select(cb.substring(c.<String>get("projDesc"), 1, 10)) It will return List<String> if you need to Return the Emp you can use the

cb.construct(Emp.class, e.get("prop1"), e.get("prop2"), cb.substring(c.<String>get("projDesc"), 1, 10)));