Rob*_*orn 6 java mysql unicode hibernate
我实际上已在Stackoverflow上多次发现此问题,但解决方案对我没有帮助.
我在我的Android应用程序中有一个聊天模块,并希望在我的服务器数据库中保留消息,这可以正常工作,直到出现像emojis这样的特殊字符.
ERROR: Incorrect string value: '\xF0\x9F\x98\x81' for column 'message' at row 1
...
...
Caused by: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x81' for column 'message' at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2838)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
... 23 more
Run Code Online (Sandbox Code Playgroud)
我的环境是:
-Mysql 5.6
-Tomcat 8.0.8
-Hibernate 4.3.5
-JDK 1.8.0_05
Run Code Online (Sandbox Code Playgroud)
这是带有问题的列的用过的表'message':

这些是我在persistence.xml(2.1版)中的属性:
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/gamedb?useUnicode=true&characterEncoding=UTF-8" />
<property name="javax.persistence.jdbc.user" value="*********" />
<property name="javax.persistence.jdbc.password" value="**************" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="utf8" />
Run Code Online (Sandbox Code Playgroud)
现在我尝试了以下解决方案,没有效果:
-Change datatype of 'message' from varchar to longtext
-Change collation of 'message' to utf8mb4
-Change collation of table to utf8mb4
-Append url with "?useUnicode=true&characterEncoding=UTF-8"
-Set character-set-server of mysql to utf8mb4
Run Code Online (Sandbox Code Playgroud)
我认为表情符号正确传输到服务器,然后它会持续显示消息,然后将其广播回应用程序并正确显示.
我曾经遇到过同样的问题.我不知道一个漂亮的解决方案,但这对我有用.
创建Session对象后,我手动更改了连接排序规则:
s.doReturningWork(new ReturningWork<Object>() {
@Override
public Object execute(Connection conn) throws SQLException
{
try(Statement stmt = conn.createStatement()) {
stmt.executeQuery("SET NAMES utf8mb4");
}
return null;
}
});
Run Code Online (Sandbox Code Playgroud)
Rob*_*orn -1
在没有收到对我的评论的进一步答复后,我找到了替代解决方案:Base64。
我没有教我的数据库理解 utf8mb4,而是在存储之前将所有关键消息编码为 Base64,并在从数据库检索它们时对其进行解码。
优点:
- 效果很好
- 已经为 java 和 android 提供了库
缺点:
- Base64 字符串比纯 utf8mb4 字符串占用更多空间(多 33%-36%)
- 可能会消耗一些编码和解码性能
| 归档时间: |
|
| 查看次数: |
7300 次 |
| 最近记录: |