Hibernate @Formula不支持查询包含'CAST()as int'函数

时间:2011-07-08 09:37:45

标签: java hibernate

以下是ExecutionHistory类的属性之一,该值是从中获取的 @Formula使用来自exectution_history表的JPA / Hibernate,

@Formula("(SELECT SUM(dividend) || '/' || SUM(divisor) " +
"FROM (SELECT CAST(substr(sr.result, 1, position('/' in sr.result)-1 ) AS int) AS dividend ," +
"CAST(substr(sr.result, position('/' in sr.result)+1 ) AS int) AS divisor " +
"FROM suite_results as sr WHERE sr.execution_history=id) AS division)")
private String result;

当我试图获取ExecutionHistory类的实例时,我发现上面的公式查询 由JPA / Hibernate转换如下:

select executionh0_.id as id7_1_, executionh0_.execution_plan as execution3_7_1_, executionh0_.start_time as start2_7_1_, 
(SELECT SUM(sr.duration) FROM suite_results as sr WHERE sr.execution_history=executionh0_.id) as formula0_1_, 
(SELECT SUM(executionh0_.dividend) || '/' || SUM(executionh0_.divisor) FROM 
(SELECT CAST(substr(sr.result, 1, position('/' in sr.result)-1 ) AS executionh0_.int) AS executionh0_.dividend , 
CAST(substr(sr.result, position('/' in sr.result)+1 ) AS executionh0_.int) AS executionh0_.divisor 
FROM suite_results as sr WHERE sr.execution_history=executionh0_.id) AS executionh0_.division) as 
formula1_1_, executionp1_.id as id6_0_, executionp1_.build_number as 
build2_6_0_, executionp1_.name as name6_0_, executionp1_.owner as owner6_0_, executionp1_.sut as sut6_0_, 
executionp1_.wait_for_page_to_load as wait6_6_0_ from execution_history executionh0_ 
left outer join execution_plans executionp1_ on executionh0_.execution_plan=executionp1_.id where executionh0_.id=?

所以问题在于,这里的公式查询包含“CAST()AS int”,但在Hibernate进行查询转换时,它会将不必要的表引用并执行为“CAST()AS executionh0_.int”,因此它给出了sql执行时语法异常。

我不知道如何避免这个问题,有人可以帮助我吗?

感谢。

2 个答案:

答案 0 :(得分:3)

这是一个老问题,但无论如何我都会发布一个答案。

如果您使用的是SQL Server数据库,则可以在要投射的类型周围添加双引号。 像这样:

@Formula("CAST(FLOOR(CAST( dat_criacao AS \"float\")) AS \"datetime\")")

答案 1 :(得分:0)

不知道您正在使用哪个数据库,但在SQL Server中,您应该在Hibernate查询中使用CONVERT而不是CAST。