Hibernate 's HQL already supports most database functions , certainly not all of them. Fortunately, Hibernate has already made a corresponding solution to this problem , that is , registering database functions in Dialect . The specific method is as follows , we take Mysql5 as an example . ( For different The database can be inherited from different database dialects, for example, oracle can check the dialect of oracle in hibernate )
Mysql 's convert function , now the character set of the database is utf-8, if you want to achieve Chinese sorting , you need to use convert (filedName using gbk) to achieve , but the existing hibernate hql can not support this function , we can now register Dialect A function is not in favor of directly modifying the source code of Hibernate . We can extend a class , as shown in the following code
import org.hibernate.Hibernate;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate ;
public class MySQL5LocalDialect extends MySQL5Dialect {
public MySQL5LocalDialect(){
super();
registerFunction("convert", new SQLFunctionTemplate(Hibernate.STRING, "convert(?1 using ?2)") );
}
}
Now modify applicationContext.xml or hibernate.hbm.xml
package.MySQL5LocalDialect
<property name="hibernate.dialect">
com.credit.publicmodel.util.MySQL5LocalDialect
</property> The convert method is now used in HQL , for example : convert(fieldName, 'gbk') , "GBK" can also be other character sets .
By the way, let's talk about the role of dialect in hibernate : dialect is "dialect", because hibernate is to convert Java objects into relational databases to describe, and relational databases have some unified standards, such as SQL-92 , etc. , but in fact, various databases such as Oracle, MySQL, MS SQL Server , etc. provide some additional standards or syntax in order to improve performance or increase functions. Therefore, hibernate is better adapted to various relational databases. A dialect dialect is specified .
You can see that the dialect in hibernate is actually just a class, which converts different data types and SQL syntax into a unified format that hibernate can understand. Note, however, that Hibernate cannot use this database for object-relational conversion without a corresponding dialect .