在HQL中使用CAST(columnName AS INT)

时间:2014-12-12 09:59:34

标签: mysql hibernate postgresql hql hibernate-4.x

我正在使用Hibernate 4和Postgres

以下查询是两个表的连接,我需要将varchar列转换为整数,以便按顺序检索某些值。 HQL是否支持此功能?文档说明了,但我得到例外如下

Query query  = session.createQuery("SELECT DISTINCT a.attributeName, a.displayName, CAST(a.seqNo AS INTEGER) FROM Entitydefinitionconcrete a, Entitymasterconcrete b WHERE (a.entityTypeId=b.concreteEntityId AND b.baseType=:baseType) AND a.viewGrid=:flag ORDER BY CAST(a.seqNo AS INTEGER)");
query.setParameter("baseType","test");
query.setParameter("flag", true);
query.list();

例外:

HHH000203: processEqualityExpression() : No expression to process!
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE, found '.' near line 1, column 70 [SELECT DISTINCT a.attributeName, a.displayName, CAST(a.seqNo AS Types.INTEGER) FROM com.tcs.oss.tims.common.entityBeans.Entitydefinitionconcrete a, com.tcs.oss.tims.common.entityBeans.Entitymasterconcrete b WHERE (a.entityTypeId=b.concreteEntityId AND b.baseType=:baseType) AND a.viewGrid=:flag ORDER BY CAST(a.seqNo AS INTEGER)]
     at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:278)
   at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)

1 个答案:

答案 0 :(得分:3)

DOC说,

cast(... as ...), where the second argument is the name of a Hibernate type, and 
extract(... from ...) if ANSI cast() and extract() is supported by the underlying database

E.G:cast(propName as integer)