1、搭建相关的项目环境mysql
2、建立类继承 org.hibernate.dialect.MySQL5InnoDBDialect(mysql)或者org.hibernate.dialect.Oracle12cDialect(oracle)spring
1 public class MySQLChineseDialect extends MySQL5InnoDBDialect { 2 3 //mysql 使JPQL支持中文排序 4 public MySQLChineseDialect() { 5 super(); 6 registerFunction("convert",new SQLFunctionTemplate(StringType.INSTANCE,"convert(?1 using gbk)")); 7 } 8 }
1 public class OracleChineseDialect extends Oracle12cDialect { 2 3 //oracle 使JPQL支持中文排序 4 public OracleChineseDialect(){ 5 super(); 6 registerFunction("convert_gbk", new SQLFunctionTemplate(StandardBasicTypes.STRING, "nlssort(?1,'NLS_SORT=SCHINESE_PINYIN_M')")); 7 } 8 9 }
3、在yml或者properties配置文件加入如下配置,使用咱们自定义方言类(重点)sql
1 spring: 2 datasource: 3 driver-class-name: com.mysql.jdbc.Driver 4 url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?characterEncoding=utf8 5 username: root 6 password: root 7 # driver-class-name: oracle.jdbc.driver.OracleDriver 8 # url: jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:scott 9 # username: scott 10 # password: scott 11 jpa: 12 properties: 13 hibernate: 14 dialect: com.cn.MySQLChineseDialect 15 # properties: 16 # hibernate: 17 # dialect: com.cn.OracleChineseDialect
4、使用oracle
//mysql环境 @Query("select o from Organizations o where o.code like :code and o.status in :status and o.belongTo = :findid and (o.department like :name or o.shortcut like :name) order by function('convert',o.department) desc ") Page<Organizations> findOrgNoZiMysqldesc(Pageable of,@Param("code") String code,@Param("status")List<Integer> status,@Param("findid")String findid,@Param("name")String name); //oracle环境 @Query("select o from Organizations o where o.code like :code and o.status in :status and o.belongTo = :findid and (o.department like :name or o.shortcut like :name) order by function('convert_gbk',o.department) desc") Page<Organizations> findOrgNoZiOracledesc(Pageable of,@Param("code") String code,@Param("status")List<Integer> status,@Param("findid")String findid,@Param("name")String name);
说明:函数
目前我试过几回以后发现没法动态修改传入的参数,也不能在Sort对象使用convert函数,只可以支持在JPQL中写死,若是大家可以发现能够动态修改参数的话,但愿留个言,指导一下。