如何在Hibernate Criteria中使用CASE子句?

时间:2016-12-26 09:51:13

标签: java spring hibernate

final Criteria criteria = session.createCriteria(getEntityClass());
            criteria.add(Restrictions.eq("preview", 1));
            return criteria.list();

如何添加投影"当id = 1然后'一个'别的' 0'最终定制" ;

类似于此,

select * , case when id = 1 then 'one ' else '0' end as custom from table where preview = 1 

1 个答案:

答案 0 :(得分:0)

我在没有Hibernate特定类的JPA接口上做过。我希望它能为你工作。我在我的本地测试它并且它正在工作

public static List<String> getUndeliveredPartnerRequests() throws Exception{

        EntityManager em = PersistenceManager.instanceEMF().createEntityManager();
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
            Root<YourEntity> entityObj = query.from(YourEntity.class);
            query.multiselect(
                    cb.selectCase()
                    .when(cb.equal(entityObj.get("preview"), 1), "one")
                    .when(cb.equal(entityObj.get("preview"), 2), "two")
                    .otherwise("wrong"));

            Query q = em.createQuery(query);
            return q.getResultList();
        } finally {
            em.close();
        }
 }