我是Hibernate的新手,我想使用Hibernate条件构建器在MySQL查询下运行。
mysql> select avg(case when id=1 then 30 when id=2 then 30 else 0 end) as avg_age from student;
我尝试过的:
CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
EntityManager em = HibernateUtil.getEntityManager();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<Student> teacher = query.from(Student.class);
query.multiselect(builder.avg(
teacher.get("salary")),
builder.selectCase()
.when(builder.equal(teacher.get("id"), 1), 30)
.when(builder.equal(teacher.get("id"), 2), 30)
.otherwise(0));
List<Object[]> results = em.createQuery(query).getResultList();
for(Object[] object: results){
System.out.println("Avg Salary = " + object[0] );
}
}
它正在分别执行avg()函数和case语句。我有一个具有id,age,salary,name,adds列的Student表,我想要avg()学生的工资,但是具有id(1和2)的学生将工资设置为30,其他人则设置为0。