Hibernate QBC对汉字进行排序

yangguirong 2011-09-26

通常在Criteria查询时,是通过criteria.addOrder(Order.asc("name"))排序;

但是默认情况下是不支持GBK格式,所以汉字无法按照拼音进行排序。下面的方法是重写HibernateOrder方法实现对汉字排序。

packagecomm;

importjava.sql.Types;

importorg.hibernate.Criteria;

importorg.hibernate.HibernateException;

importorg.hibernate.criterion.CriteriaQuery;

importorg.hibernate.criterion.Order;

importorg.hibernate.engine.SessionFactoryImplementor;

importorg.hibernate.type.Type;

publicclassGBKOrderextendsOrder{

privateStringencoding="GBK";

privatebooleanascending;

privatebooleanignoreCase;

privateStringpropertyName;

@Override

publicStringtoString(){

return"CONVERT("+propertyName+"USING"+encoding+")"+(ascending?"asc":"desc");

}

@Override

publicOrderignoreCase(){

ignoreCase=true;

returnthis;

}

/**

*ConstructorforOrder.

*/

protectedGBKOrder(StringpropertyName,booleanascending){

super(propertyName,ascending);

this.propertyName=propertyName;

this.ascending=ascending;

}

/**

*ConstructorforOrder.

*/

protectedGBKOrder(StringpropertyName,Stringdir){

super(propertyName,dir.equalsIgnoreCase("ASC")?true:false);

ascending=dir.equalsIgnoreCase("ASC")?true:false;

this.propertyName=propertyName;

this.ascending=ascending;

}

/**

*RendertheSQLfragment

*

*/

@Override

publicStringtoSqlString(Criteriacriteria,CriteriaQuerycriteriaQuery)throwsHibernateException{

String[]columns=criteriaQuery.getColumnsUsingProjection(criteria,propertyName);

Typetype=criteriaQuery.getTypeUsingProjection(criteria,propertyName);

StringBufferfragment=newStringBuffer();

for(inti=0;i<columns.length;i++){

SessionFactoryImplementorfactory=criteriaQuery.getFactory();

booleanlower=ignoreCase&&type.sqlTypes(factory)[i]==Types.VARCHAR;

if(lower){

fragment.append(factory.getDialect().getLowercaseFunction()).append('(');

}

fragment.append("CONVERT("+columns[i]+"USING"+encoding+")");

if(lower)

fragment.append(')');

fragment.append(ascending?"asc":"desc");

if(i<columns.length-1)

fragment.append(",");

}

returnfragment.toString();

}

/**

*Ascendingorder

*

*@parampropertyName

*@returnOrder

*/

publicstaticOrderasc(StringpropertyName){

returnnewGBKOrder(propertyName,true);

}

/**

*Descendingorder

*

*@parampropertyName

*@returnOrder

*/

publicstaticOrderdesc(StringpropertyName){

returnnewGBKOrder(propertyName,false);

}

}

但是如果用上面的方法之后。数字的排序就达不到预期的目的了,需要利用反射对java类的属性进行判断,查看其类型:

Class<?>c=object.getClass().getField(str).getType();

System.out.println(c.getName());

通过判断类型的不同进行部不同的处理。

相关推荐

LetonLIU / 0评论 2020-05-29
东方咖啡屋 / 0评论 2020-01-06