QueryDSL like operation SimplePath

会有一股神秘感。 提交于 2019-12-11 09:59:10

问题


Similarly to this question I would like to perform an SQL "like" operation using my own user defined type called "AccountNumber".

The QueryDSL Entity class the field which defines the column looks like this:

public final SimplePath<com.myorg.types.AccountNumber> accountNumber;

I have tried the following code to achieve a "like" operation in SQL but get an error when the types are compared before the query is run:

final Path path=QBusinessEvent.businessEvent.accountNumber;
final Expression<AccountNumber> constant = Expressions.constant(AccountNumber.valueOfWithWildcard(pRegion.toString()));
final BooleanExpression booleanOperation = Expressions.booleanOperation(Ops.STARTS_WITH, path, constant);
expressionBuilder.and(booleanOperation);

The error is:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [7!%%] did not match expected type [com.myorg.types.AccountNumber (n/a)]

Has anyone ever been able to achieve this using QueryDSL/JPA combination?


回答1:


Did you try using a String constant instead?

Path<?> path = QBusinessEvent.businessEvent.accountNumber;
Expression<String> constant = Expressions.constant(pRegion.toString());
Predicate predicate = Expressions.predicate(Ops.STARTS_WITH, path, constant);



回答2:


In the end, I was given a tip by my colleague to do the following:

 if (pRegion != null) {
        expressionBuilder.and(Expressions.booleanTemplate("{0} like concat({1}, '%')", qBusinessEvent.accountNumber, pRegion));
 }

This seems to do the trick!




回答3:


It seems like there is bug/ambiguity. In my case, I need to search by couple fields with different types (String, Number), e.g. SQL looks like:

SELECT * FROM table AS t WHERE t.name = "%some%" OR t.id = "%some%";

My code looks like:

BooleanBuilder where = _getDefaultPredicateBuilder();
BooleanBuilder whereLike = new BooleanBuilder();
for(String likeField: _likeFields){
    whereLike = whereLike.or(_pathBuilder.getString(likeField).contains(likeValue));
}
where.and(whereLike);

If first _likeFields is type of String - request works fine, otherwise it throws Exception.



来源:https://stackoverflow.com/questions/32400722/querydsl-like-operation-simplepath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!