Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL + PathBuilder + cast to string

I am filtering PrimeFaces DataTables using dynamic filters.I have this working using Spring org.springframework.data.jpa.domain.Specification.Now I am wondring how to do the same using QueryDSL.

Using specification I can use javax.persistence.criteria.Root to get a javax.persistence.criteria.Join, use javax.persistence.criteria.Expression.as(Class<String> type) to cast it to String and finally use javax.persistence.criteria.CriteriaBuilder.like(Expression<String> x, String pattern, char escapeChar).

How do I do the same in QueryDSL ? I can get PathBuilder using new PathBuilder<T>(clazz, "entity") (do you really have to use the variable here? I would like my class to be generic...) but then the com.mysema.query.types.path.PathBuilder.get(String property) returns new PathBuilder instead of an Expression.

If I try to use com.mysema.query.types.path.PathBuilder.getString(String property) I get java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer].

Seems like the part I am missing is the cast. I'm quite sure someone was dealing with the same thing already.

Thanks.

Edit: Stack trace for IllegalArgumentException

Trying to search for text "1" inside integer column using com.mysema.query.types.path.PathBuilder.getString(String property) - that's where I need the cast to happen :

Caused by: java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer] at org.hibernate.ejb.AbstractQueryImpl.validateParameterBinding(AbstractQueryImpl.java:375) at org.hibernate.ejb.AbstractQueryImpl.registerParameterBinding(AbstractQueryImpl.java:348) at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:375) at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:442) at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72) at com.mysema.query.jpa.impl.JPAUtil.setConstants(JPAUtil.java:44) at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:130) at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:97) at com.mysema.query.jpa.impl.AbstractJPAQuery.list(AbstractJPAQuery.java:240) at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:102) ...

like image 671
user1622058 Avatar asked Mar 30 '15 13:03

user1622058


1 Answers

To get a valid condition you will need to take the types of the properties into account, e.g.

pathBuilder.getNumber(Integer.class, property).stringValue().like(likePattern)
like image 127
Timo Westkämper Avatar answered Sep 30 '22 13:09

Timo Westkämper