在hibernate中选择列并编写案例

在hibernate中选择列并编写案例,hibernate,nhibernate,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; 有人能帮忙吗?我们可以这样做: 首先,让我们创建一个条件,稍后进行计算: var computed = Projections.Conditional( Restrictions.Gt("

我想为查询编写分离的条件

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

有人能帮忙吗?

我们可以这样做:

首先,让我们创建一个条件,稍后进行计算:

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>();
public class EmployeeDTO
{
    public virtual int ID { get; set; }
    public virtual int Total { get; set; }
    public virtual int Salary { get; set; }
}