Java的休眠Projections.sqlGroupProjection走样(Java Hiber

2019-10-31 04:22发布

我有一个Criteria使用Hibernate这样的

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

所以。

我试图让SUM中的DiscriminatorValue通过分组DiscriminatorColumn

我的意思是,如果我通过过滤在前面的例子中DiscriminatorColumn = 1我将接收SUM=16

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我找不到休眠填充的方式sumdiscriminatorValue列结果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

我已经写我自己的变压器这一点,但它是一种烦人。

Answer 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"));

只是包装你的sqlGroupProjectionsProjection.alias为设置别名你的财产在你的匹配Java class和Hibernate将与和结果,而不是填充custom transformer are not longer required ..

我希望可以帮助别人。



文章来源: Java Hibernate Projections.sqlGroupProjection aliasing