Hibernate标准没有使用投影别名

时间:2010-05-19 17:47:14

标签: java hibernate

Hibernate Projection别名是否有效?我发誓它不会发誓。至少,它没有做我期望它做的事情。

这是java:

return sessionFactory.getCurrentSession()
    .createCriteria(PersonProgramActivity.class)
    .setProjection(Projections.projectionList()
        .add(Projections.alias(Projections.sum("numberOfPoints"), "number_of_points"))
        .add(Projections.groupProperty("person.id")))
    .setFirstResult(start)
    .setFetchSize(size)
    .addOrder(Order.desc("numberOfPoints"))
    .list();

以下是它生成的SQL:

select
    sum(this_.number_of_points) as y0_,
    this_.person_id as y1_
from
    PERSON_PROGRAM_ACTIVITY this_
group by
    this_.person_id
order by
    this_.number_of_points desc

似乎根本没有使用别名。我认为设置别名意味着sum(this_.number_of_points)将别名为number_of_points而不是y0_。我缺少一些技巧吗?

感谢。

2 个答案:

答案 0 :(得分:6)

您需要为整个条件指定别名,然后您可以创建实际使用的其他别名。奇怪的是,别名变成y0_而不是相反。

return sessionFactory.getCurrentSession()
    .createCriteria(PersonProgramActivity.class, "ppa")
    .setProjection(Projections.projectionList()
        .add(Projections.alias(Projections.sum("numberOfPoints"), "ppa.numberOfPoints"))
        .add(Projections.groupProperty("person.id")))
    .setFirstResult(start)
    .setFetchSize(size)
    .addOrder(Order.desc("ppa.numberOfPoints"))
    .list();

生成以下SQL:

select
    sum(this_.number_of_points) as y0_,
    this_.person_id as y1_
from
    PERSON_PROGRAM_ACTIVITY this_
group by
    this_.person_id
order by
    this_.y0_ desc

答案 1 :(得分:1)

查询应为

return sessionFactory.getCurrentSession()
    .createCriteria( PersonProgramActivity.class, "ppa" )
    .setProjection(Projections.projectionList()
        .add( Projections.alias( Projections.sum( **"ppa.numberOfPoints"** ), **"numberOfPoints"** ) )
        .add( Projections.groupProperty( "person.id" ) ) )
    .setFirstResult( start )
    .setFetchSize( size )
    .addOrder( Order.desc( "ppa.numberOfPoints" ) )
    .list();