How to pass an argument to a function when using ParameterExpression together with org.springframework.data.jpa.domain.Specification?

若如初见. 提交于 2019-12-11 04:08:36

问题


I am using org.springframework.data.jpa.domain.Specification together with JpaSpecificationExecutor to easily create queries with conditions in Java but now I need to call a MySQL DB function that returns an integer value.

The problem is that it is unclear how to pass an argument for this function as I am not using TypedQuery:

// cb here is CriteriaBuilder
ParameterExpression param = cb.parameter(String.class);

Predicate predicate = cb.greaterThan(cb.function("A_FUNCTION", 
      Integer.class, param), 0);

Specification spec = cb.and(predicate);

// query is executed like this

return (int) repositoryThatExtendsJpaSpecificationExecutor.count(test);

And the example from here is not helping.


回答1:


I think what you really need is a literal which you can create using CriteriaBuilder.literal. A full example would look like

// cb here is CriteriaBuilder
Expression param = cb.literal("Stephen Hawking");

Predicate predicate = cb.greaterThan(cb.function("A_FUNCTION", 
      Integer.class, param), 0);

Specification spec = cb.and(predicate);

If the value doesn't come from your application you can use (m)any of the functions returning an Expression.



来源:https://stackoverflow.com/questions/49304067/how-to-pass-an-argument-to-a-function-when-using-parameterexpression-together-wi

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