Some CriteriaBuilder's methods specified by JPA (like, notLike, concat, substring, trim, lower, upper, length, locate) can only work with strings thus rejecting the integer expression:
predicates.add(
Expression<Long> idExpr = root.get(Contact_.id);
builder.like(idExpr), // error: Expression<String> is expected
builder.literal(searchCriteria.getContactId() + "%")
);
To workaround the problem you may try to use Hibernate extensions, for example:
- HCQ (Hibernate Criteria Query) with a little help of a native SQL
Criteria c = session.createCriteria(Contact.class);
c.add(Restrictions.sqlRestriction(" CAST(id AS varchar(255)) LIKE '1%'"));
List<Contact> entities = c.list();
- HQL (Hibernate Query Language)
Query q = session.createQuery("FROM Contact c WHERE STR(c.id) LIKE '1%'");
List<Contact> c= q.list();
SQLQuery q2 = session.createSQLQuery("SELECT * FROM Contact " +
"WHERE CAST(id AS varchar(255)) LIKE '1%'");
List<Contact> entities = q.getResultList();
Looks like only HQL has STR()
expression or I cannot find equivalent in HCQ. Anyway STR(c.id)
used in HQL will be translated to CAST(id AS VARCHAR(255))
clause.