JPA: How to perform a LIKE with a NUMBER column in a static JPA MetaModel?

前端 未结 2 1099

I do have a static metamodel with a NUMBER (actually, BigDecimal, don\'t ask why) column. Now I would like to do a LIKE query against that number column:

Cri         


        
相关标签:
2条回答
  • 2021-01-14 06:47

    No, it does not fail because of bug, it works as specified (for example in Javadoc):

    Perform a typecast upon the expression, returning a new expression object. This method does not cause type conversion: the runtime type is not changed. Warning: may result in a runtime failure.

    Method you use performs cast and you need conversion. In general there is no support to convert from BigDecimal to String in JPA.

    0 讨论(0)
  • 2021-01-14 06:57

    For the people, who are still looking for a solution.

    Knowing that HQLstr function does the job (at least for Hibernate v. 3.6.9.Final) one can implement his own FunctionExpression like:

    //plagiarized from org.hibernate.ejb.criteria.expression.function.CastFunction
    public class StrFunction<Y extends Number> extends BasicFunctionExpression<String> implements FunctionExpression<String>, Serializable {
        public static final String FCT_NAME = "str";
    
        private final Selection<Y> selection;
    
        public StrFunction(CriteriaBuilder criteriaBuilder, Selection<Y> selection) {
            super((CriteriaBuilderImpl) criteriaBuilder, String.class, FCT_NAME);
            this.selection = selection;
        }
    
        @Override
        public void registerParameters(ParameterRegistry registry) {
            Helper.possibleParameter(selection, registry);
        }
    
        @Override
        public String render(CriteriaQueryCompiler.RenderingContext renderingContext) {
            return FCT_NAME + '(' + ((Renderable) selection).render(renderingContext) + ')';
        }
    }
    

    and then use it:

    cb.like(new StrFunction<Long> (cb, root.get(MyObject_.id)), "%mySearchTerm%");
    
    0 讨论(0)
提交回复
热议问题