jpa註冊函數(實現oracle/mysql的中文排序 spring-boot環境)

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中寫死,若是大家可以發現能夠動態修改參數的話,但願留個言,指導一下。
相關文章
相關標籤/搜索