2015-05-13 93 views
0

我有一個Criteria使用休眠這樣爪哇休眠Projections.sqlGroupProjection走樣

public class Student 
{ 
    private Integer id,discriminatorColumn,discriminatorValue; 
    //other stuff omitted for brevity 
} 

該實體具有discriminatorColumn,其具有1至10(永不NULL)值,並且每個discriminatorColumn具有discriminatorValue其具有值從1 to 100(從不NULL

實施例:(學生數據)

ID DiscriminatorColumn DiscriminatorValue 
1   1     3 
2   2     4 
3   1     13 

等等。

我試圖通過DiscriminatorColumn

我的意思是,如果我通過DiscriminatorColumn = 1篩選前面的例子中我會收到SUM=16得到DiscriminatorValue分組的SUM

final Criteria criteria = session.createCriteria(Student.class) 
.setProjection(Projections.sqlGroupProjection(
    "sum({alias}.discriminatorValue) as rowCount", 
    "hibernateAlias.discriminatorColumn having rowCount>0", 
    new String[]{"rowCount"}, 
    Helper.HIBERNATE_INTEGER_INSTANCE 
)); 

這將創建rightSQL我看到這樣的事情

select sum(discriminatorValue) as rowCount 
from student 
group by discriminator_column 
having rowCount>0 

我的問題是,當我設置resultSetTransformer到Student.class我找不到休眠的方式填充discriminatorValuesum導致在discriminatorValue Java領域。

我認爲,爲此目的是使用下面的參數new String[]{"rowCount"}

但我已經試過

new String[]{"discriminatorValue"} 
new String[]{"this.discriminatorValue"} 
new String[]{"{alias}.discriminatorValue"} 
new String[]{"{studentAlias}.discriminatorValue"} using alias in Criteria 
new String[]{"rowCount as discriminatorValue"} 
new String[]{"rowCount as this_.discriminatorValue"} 
and So On.. 

但似乎是不可能的什麼,我做錯了什麼?這是不可能的? Sum the values as set it as a simple Property as retrieving regular from database

我已經寫了我自己的變壓器,但它有點煩人。

回答

1

我自己找到了答案,我會在這裏發佈能夠幫助別人。

Projections.sqlGroupProjection("sum({alias}.discriminatorValue) as rowCount","hibernateAlias.discriminatorColumn having rowCount>0",new String[]{"rowCount"},Helper.HIBERNATE_INTEGER_INSTANCE) 

似乎rowCount混疊new String[]{"rowCount"}只是針對MySQL的句法,或者只是Criteria engine忽視的是,你需要使用一個別名您EntityClass使用outer alias instead來填充屬性。

例子:

yourProjections.add(Projections.alias(Projections.sqlGroupProjection("sum({alias}.discriminatorValue) as rowCount","hibernateAlias.discriminatorColumn having rowCount>0",new String[]{"rowCount"},Helper.HIBERNATE_INTEGER_INSTANCE),"discriminatorValue")); 

只是包裝你sqlGroupProjections作爲設置別名你的財產你Java class匹配和Hibernate將與求和結果填充,而不是一個custom transformer are not longer required ... Projection.alias

我希望幫助有人。