hibernate用起来是非常方便,但是还是没有自己写sql那么方便,比如自己定义一个排序方式可以用
case 要排序的字段 when '42' then 1
when '137' then 2
when '136' then 3
end;
这样就可以实现自定义排序,但是new DetachedCriteria().addOrder(Order.desc("要排序的字段"));
只能根据一个字段的升序和降序,想要实现自定义就必须继承Order父类然后重写
贴上代码
/** * OracleOrder.java * com.cl.business.pcdm.util * 2017年12月29日 Shinelon * * Copyright (c) 2017, TNT All Rights Reserved. */ package com.cl.business.pcdm.util; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Order; /** * ClassName:OracleOrder * Function: TODO 自定义order 排序 * * @author lxw * @version * @since JDK1.7 * @Date 2017 2017年12月29日 下午4:30:37 * * @see 参考目标类 */ public class OracleOrder extends Order { /** * serialVersionUID:TODO(用一句话描述这个变量表示什么) * * @since JDK1.7 */ private static final long serialVersionUID = 1L; private String propertyName; private boolean ascending; protected OracleOrder(String propertyName, boolean ascending) { super(propertyName, ascending); this.propertyName = propertyName; this.ascending = ascending; } public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName); //在这里自定义你的字段 return " case "+columns[0]+" when '42' then 1 " + "when '138' then 2 " + "when '136' then 3 " + "when '137' then 4 end "; } public static OracleOrder getOrder(String propertyName ) { return new OracleOrder(propertyName, true); } }
//最后在你的类中引用 new DetachedCriteria().addOrder(OracleOrder.getOrder("要排序的字段")) ;