在hibernate中选择列和写案例

时间:2013-10-11 06:17:03

标签: hibernate nhibernate

我想为查询编写分离标准。

SELECT Id, sum(1) as total 
    ,sum(CASE WHEN e.salary > 2000 THEN e.salary
         ELSE 2000 END) "total Salary" 
FROM employees e;

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我们可以这样做:

首先让我们创建条件,稍后再计算:

var computed = Projections.Conditional(
    Restrictions.Gt("Salary", 2000)
    , Projections.Property("Salary")
    , Projections.Constant(2000));

此时,我们将CASE语句包含在computed投影中。所以让我们使用它:

var session = ... // get the ISession 

// criteria querying the Employee
var criteria = session.CreateCriteria<Employee>();

// the projections we need
criteria.SetProjection(
    Projections.ProjectionList()
        .Add(Projections.GroupProperty("Id"), "Id")
        .Add(Projections.Sum(Projections.Constant(1)), "Total")
        .Add(Projections.Sum(computed), "Salary")
    );

// result transformer, converting the projections into EmployeeDTO
var list = criteria
    .SetResultTransformer(Transformers.AliasToBean<EmployeeDTO>())
    .List<EmployeeDTO>();

如果Salary是int:

,这可能是我们的EmployeeDTO
public class EmployeeDTO
{
    public virtual int ID { get; set; }
    public virtual int Total { get; set; }
    public virtual int Salary { get; set; }
}