Mysql数据库下Hibernate按中文姓名排序

项目使用的Mysql + Hibernate框架,最近用到了按中文排序,按照之前英文排序的方法,发现结果不成功,原来Mysql中utf8mb4编码的数据按中文排序要先转GBK,

SELECT *
FROM mb_member t    
WHERE 1=1 

ORDER BY CONVERT(full_name USING gbk) asc

这样排出来的结果就完全按照中文来排序了,但是如果直接把convert放到Hibernate的HSQ中,肯定是不行的,会报“unexpected token: USING”错误。

这就需要在Mysql的方言中注册一个方法,共两步:

一、继承 MySQL57InnoDBDialect 写下自己的方言类

import org.hibernate.dialect.MySQL57InnoDBDialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.type.StringType;

public class MySQLLocalDialect extends MySQL57InnoDBDialect {

    public MySQLLocalDialect(){
        super();
        registerFunction("convert",new SQLFunctionTemplate(StringType.INSTANCE, "convert(?1 using ?2)") );
    }

}

二、修改Hibernate配置方言指向自己的方言类



至此就可以了,使用时: convert(t.fullName , 'gbk')  会自己转换为 convert(full_name USING gbk)

SELECT DISTINCT t FROM MbMemberEntity t WHERE 1=1 ORDER BY convert(t.fullName , 'gbk') asc

解决问题中要感谢以下博客:

1. http://liugang-ok.iteye.com/blog/1167859

2. http://blog.csdn.net/zhichao2001/article/details/11721325

3. http://www.iteye.com/problems/94206


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用JPA生成MYSQL数据库表时,可以设置表的默认排序规则。MYSQL的默认排序规则取决于服务器的配置,一般情况下,MYSQL的默认排序规则是utf8mb4_general_ci。 要设置JPA生成MYSQL数据库表的排序规则,可以在application.properties或application.yml文件中添加以下配置: ``` spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=Asia/Shanghai&useSSL=false spring.datasource.username=root spring.datasource.password=123456 spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.hbm2ddl.charset=utf8mb4 spring.jpa.properties.hibernate.connection.CharSet=utf8mb4 spring.jpa.properties.hibernate.connection.useUnicode=true spring.jpa.properties.hibernate.connection.characterEncoding=utf-8 ``` 其中,spring.jpa.database-platform和spring.jpa.properties.hibernate.dialect都指定了使用的数据库方言,这里使用的是MySQL8Dialect。spring.jpa.properties.hibernate.connection.CharSet、spring.jpa.properties.hibernate.connection.useUnicode和spring.jpa.properties.hibernate.connection.characterEncoding指定了数据库的字符编码和字符集。spring.jpa.properties.hibernate.hbm2ddl.charset指定了DDL生成文件的编码,这里也设置为utf8mb4。最后,需要在数据库连接字符串中添加useUnicode=true和characterEncoding=utf8mb4,确保JPA能够正确地处理UTF-8编码的字符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值