JPA Query中的Cast字段

时间:2015-06-09 13:12:32

标签: java mysql sql-server jpa

在我的sql-server中,字段DATE以浮动格式保存(es:DATADOC = 42155

我想将mysql DB中的字段导入为DATETIME。 我尝试在sql-server上使用此查询来转换字段:

SELECT CAST(DATDOC as DATETIME) -2 FROM FATTURE where id=25460;

结果是正确的。

现在,我想在JPA Query中翻译它:

TypedQuery<DateTime> convFattura = emI24.createQuery(" SELECT CAST(dataFattura as DATETIME) -2 FROM FatturaI24 f where f.id = :idFattura", DateTime.class);

但我收到了这个错误:

    09-06-2015 14:32:00 ERROR: org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
java.lang.NullPointerException
    at org.hibernate.dialect.function.CastFunction.render(CastFunction.java:55)
    at org.hibernate.hql.internal.ast.SqlGenerator.endFunctionTemplate(SqlGenerator.java:220)
    at org.hibernate.hql.internal.antlr.SqlGeneratorBase.methodCall(SqlGeneratorBase.java:2326)
    at org.hibernate.hql.internal.antlr.SqlGeneratorBase.simpleExpr(SqlGeneratorBase.java:2681)
    at org.hibernate.hql.internal.antlr.SqlGeneratorBase.expr(SqlGeneratorBase.java:1476)

DATETIME中CAST的正确语法是什么?

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试使用Convert函数而不是Cast函数。 它对我有用......!

答案 1 :(得分:0)

正如你在评论中所说的那样,返回值是一个浮点类型,所以我们要做的就是不在sql中进行转换,而是使用java代码转换float,并且你有正确的代码:

Query convFattura = emI24.createQuery(" SELECT f.dataFattura FROM FatturaI24 f where f.id = :idFattura");
            convFattura = convFattura.setParameter("idFattura", idFatturaValue);  
        float dataFattura = convFattura.getSingleResult(); 

将float转换为日期的java代码:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.add(Calendar.HOUR_OF_DAY, (int) dataFattura);
calendar.set(Calendar.MINUTE, (int) ((dataFattura * 60) % 60));
calendar.set(Calendar.SECOND, (int) ((dataFattura * 3600) % 3600));

DateFormat fmt = new SimpleDateFormat();
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); 
System.out.println(fmt.format(calendar.getTime()));

希望对你有用!