本例项目源码地址
本文内容前提建立在自己对Jpa和hibernate有所了解。由于自己比较喜欢使用Gradle作为构建工具,所以项目基本都使用Gradle为例。如果本文有存在错误,希望大家指出说明。
准备工作
使用Spring boot作为基本环境,添加相关依赖。数据库这里采用Mysql
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile 'mysql:mysql-connector-java'
}
了解 SQLFunction
从SQLFunction的注释中可以知道它用于进行HQL 和SQL函数的转换。
接口如下:
public interface SQLFunction {
public boolean hasArguments();
public boolean hasParenthesesIfNoArguments();
public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException;
/**
* Render the function call as SQL fragment.
* <p/>
* Note, the 'firstArgumentType' parameter should match the one passed into {@link #getReturnType}
*
* @param firstArgumentType The type of the first argument
* @param arguments The function arguments
* @param factory The SessionFactory
*
* @return The rendered function call
*
* @throws org.hibernate.QueryException Indicates a problem rendering the
* function call.
*/
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException;
}
getReturnType:表明了函数的返回值类型,例如MySQL中sqrt函数返回值为DOUBLE,一些基本的返回值都定义在StandardBasicTypes类中。
render:此方法将自定义的函数转换为具体数据库对应数据库函数。
创建自定义Dialect
在hibernate中,一些基本常用的sql 函数都会在Dialect定义注册,以mysql为例,一些常见的函数都在Dialect的构造方法中注册。
registerFunction( "abs", new StandardSQLFunction( "abs" ) );
registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) );
registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) );
registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) );
registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) );
...
所以想要添加自定义函数,只需要继承相关Dialect,在构造中注册自己的函数即可。
public class CustomMysql5Dialect extends MySQL5Dialect {
public CustomM