从数据库中查找数据并按首字母排序

来源:互联网 发布:mac战网该服务器 编辑:程序博客网 时间:2024/05/29 13:42
      在SQL语句中,在检索语句的最后加上一个order by+排序列名就可以对该列的数据进行排序。排序的方式有两种:升序(ASC)和降序(DSC)。

      前些天修改项目代码时发现,按照这种规则实现排序时,只有当数据库表中的数据为英文时,才可以正确排序,当表中的数据为中文时,就不能按照中文的首字母对数据进行排序。究其原因发现,存储字段使用的是utf-8字符集,所以在排序时,需要先对排序字段进行转码。

      以下是在myeclipse上的实现过程:

(1)首先新建一个MySQLLocalDialect类对MySQLDialect进行扩展

package utils;
import org.hibernate.Hibernate;  
import org.hibernate.dialect.MySQLDialect;  
import org.hibernate.dialect.function.SQLFunctionTemplate;  
import org.hibernate.type.StringType;

public class MySQLLocalDialectextends MySQLDialect{
public MySQLLocalDialect(){ 
        super();
        registerFunction("convert_gbk" 
                new SQLFunctionTemplate(Hibernate.STRING,"convert(?1 using gbk)") ); 
    }
}

(2)修改applicationContext-hibermate.xml中的配置

<propertyname="hibernateProperties">
      <props
>
        <propkey="hibernate.dialect">utils.MySQLLocalDialect<
/prop>

        ……

     </props>

</property>
(3)再写查询语句就可以了。

String SQL="from CourseTeacher a where a.worker.workerId=? order by convert_gbk(a.course.name)";