Hibernate builds tables default to UTF-8 encoding

1. Question:

The encoding of hibernate's automatic table creation should be the default encoding format of the data, generally not utf-8. So if you want to create a table, the default encoding is UTF-8, what should you do?

Second, the solution:

Take mysql as an example:

(1), modify the dialect of hibernate to build tables

1. In general, the mysql dialect we use is: org.hibernate.dialect.MySQL5Dialect

The default returned is

@Override  
    public String getTableTypeString() {  
        return " ENGINE=InnoDB";  
    }  

2. Rewrite the MySQL5InnoDBDialect class and override the getTableTypeString method

package com.lqy.spring.hibernate.mysql;  
  
import org.hibernate.dialect.MySQL5InnoDBDialect;  
  
public class MySQL5DialectUTF8 extends MySQL5InnoDBDialect{  
  
    @Override  
    public String getTableTypeString() {  
        return " ENGINE=InnoDB DEFAULT CHARSET=utf8";    
    }  
}  

3. The dialect configuration uses our rewritten class, and the configuration is as follows:

 

(1) Jpa database connection configuration:

put the default configuration

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />  

changed to

<property name="hibernate.dialect" value="com.lqy.spring.hibernate.mysql.MySQL5DialectUTF8" />  

(2) Spring integrates hibernate configuration:

<prop key="hibernate.dialect">com.lqy.spring.hibernate.mysql.MySQL5DialectUTF8</prop>  
<property name="jpaProperties">  
            <props>  
              
                  
                <!-- Automatically create table type validate|create|create-drop|update -->  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <!-- Whether to display SQL -->  
                <prop key="hibernate.show_sql">false</prop>  
                <!-- Displays whether the SQL is formatted -->  
                <prop key="hibernate.format_sql">false</prop>  
                <prop key="hibernate.dialect">com.lqy.spring.hibernate.mysql.MySQL5DialectUTF8</prop>  
            </props>  
        </property>  

4. Modify the data connection Url

jdbc.url=jdbc:mysql://192.168.1.11:3306/db?useUnicode=true&characterEncoding=UTF-8

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325025326&siteId=291194637