錯誤信息:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy111.executeUpdate(Unknown Source)
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56)
... 37 common frames omitted
原因:
開啟hibernate的sql語句顯示可以看到hibernate在幫我們創(chuàng)建表的時候,字符串類型用的是varchar(255),而mysql支持的最大varchar長度是255.666 ,但前提條件是要用utf8字符集,也就是mysql的varchar最大支持767個字節(jié)(一個utf8=3個字節(jié)),但不知是什么原因,默認(rèn)情況下hibernate用varchar(255)會報上面的錯誤(猜測:可能hibernate默認(rèn)用的不是utf8而是其他類似于utf16這樣的大于3字節(jié)的字符集)
解決方法:
在數(shù)據(jù)庫的連接配置的url上手動指定采用utf8字符集(jdbc:mysql://localhost:3306/doll_paidb?&useUnicode=true&characterEncoding=utf8)
對應(yīng)springboot 的yaml配置文件寫法如下:
spring:
datasource:
username: helll
password: xxxx123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://server.yidou360.com:3306/doll_pai_erp_basic?&useUnicode=true&characterEncoding=utf-8
然后修改數(shù)據(jù)庫字符集,mysql命令:alter database mydb character set utf-8;