java.sql.SQLException: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) a

在项目中遇到一个这样的错误,一看知道是字符集的问题。

那么去查看数据库 的字符集

mysql > show variables like '%character%';


可是呢,字符集没问题,再看:

mysql > SHOW VARIABLES LIKE 'collation_%';



 还是没问题,这就尴尬了,为什么呢。

在网上看了看,有说去查看表的字符编码的。于是去看了 表的字符编码。果然问题出在了这里:

将如下字符集改成utf8


 

再经测试,完美。

原因:

出现上述原因是建表的时候使用的hibernate自动建表。hibernate使用的方言是:org.hibernate.dialect.MySQL5Dialect ,

查看源码可以看到

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

里面是这样的。

解决方法:

我们可以继承MySQL5InnoDBDialect类重写 getTableTypeString方法

import org.hibernate.dialect.MySQL5InnoDBDialect;

public class CustomerMySqlDialect  extends MySQL5InnoDBDialect{

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

然后在jdbc.properties中加入:

jdbc.url=jdbc:mysql://localhost:3306/exam?useUnicode\=true&characterEncoding\=UTF-8

在xml中引用自定义的方言即可 

<prop key="hibernate.dialect">com.exam.bean.common.CustomerMySqlDialect</prop> 


 

猜你喜欢

转载自1960370817.iteye.com/blog/2399674