如何使用JPA2 Criteria API将字符串正确地转换为数字? [英] How to properly cast string to number with JPA2 Criteria API?

查看:466
本文介绍了如何使用JPA2 Criteria API将字符串正确地转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用subselect编写查询,该查询将字符串强制转换为长整型. 我可能丢失了什么?

I am trying to write a query with subselect where a string is cast to a long. I'm probably missing something?

查询如下:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Task> query = cb.createQuery(Task.class);

Root<Task> from = query.from(Task.class);

Subquery<Long> subquery = query.subquery(Long.class);
Root<EntityKeyword> fromKeyword = subquery.from(EntityKeyword.class); 
subquery.select(fromKeyword.get(EntityKeyword_.relatedToId).as(Long.class));
subquery.where(cb.like(fromKeyword.get(EntityKeyword_.keyword), term));

query.where(cb.in(from.get(ModelEntity_.id)).value(subquery));

其中 EntityKeyword_.relatedToId 是要转换为Long的字符串.

Where EntityKeyword_.relatedToId a is String that requires cast to Long.

但是底层的Hibernate失败,并带有异常:

But underlying Hibernate fails with exception:

Last cause: No data type for node: org.hibernate.hql.ast.tree.MethodNode 
 \-[METHOD_CALL] MethodNode: '('
    +-[METHOD_NAME] IdentNode: 'cast' {originalText=cast}
    \-[EXPR_LIST] SqlNode: 'exprList'
       +-[DOT] DotNode: 'entitykeyw1_.keyword' {propertyName=keyword,dereferenceType=ALL,propertyPath=keyword,path=generatedAlias1.keyword,tableAlias=entitykeyw1_,className=l.i.s.m.s.EntityKeyword,classAlias=generatedAlias1}
       |  +-[ALIAS_REF] IdentNode: 'entitykeyw1_.id' {alias=generatedAlias1, className=l.i.s.m.s.EntityKeyword, tableAlias=entitykeyw1_}
       |  \-[IDENT] IdentNode: 'keyword' {originalText=keyword}
       \-[IDENT] IdentNode: 'int8' {originalText=int8}

不知道怎么了.感谢您的帮助.

No idea what's wrong. Any help is appreciated.

我正在使用Hibernate 3.6.8-Final

I'm using Hibernate 3.6.8-Final

推荐答案

Criteria API中没有方法可以执行从String到Long的转换.

There is no method in Criteria API that performs conversion from String to Long.

您尝试在 Expression 中使用方法 as 进行转换. Javadoc 解释了为什么最终会遇到运行时问题:

You try to use method as in Expression to make this conversion. Javadoc explains why you end up to have runtime problems:

对表达式执行类型转换,返回新的表达式 目的.此方法不会导致类型转换:运行时类型 不变.警告:可能会导致运行时失败.

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.

CriteriaBuilder确实具有方法束用于类型转换,但也不支持字符串到数字的转换.

CriteriaBuilder does have bunch of methods for typecast, but also no support for string-to-numeric conversion.

这篇关于如何使用JPA2 Criteria API将字符串正确地转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆