【问题标题】:saving emoji to mysql using hibernate Incorrect string value: '\xF0\x9F\x98\x88\xF0\x9F...' for column 'name' at row 1使用休眠将表情符号保存到 mysql 不正确的字符串值:'\xF0\x9F\x98\x88\xF0\x9F...' for column 'name' at row 1
【发布时间】:2020-11-13 08:26:30
【问题描述】:

我的连接字符串具有以下属性 useUnicode=true&characterEncoding=utf8&character_set_server=utf8mb4&charset=utf8mb4

我用过

    jpaProperties.put("hibernate.connection.useUnicode", true);
    jpaProperties.put("hibernate.connection.characterEncoding", "utf8");
    jpaProperties.put("hibernate.connection.CharSet", "utf8mb4");

数据库也支持 utf8mb4,因为当我手动添加记录时,它会正确保存

尝试保存表情符号时仍然出现错误

Incorrect string value: '\xF0\x9F\x98\x88\xF0\x9F...' for column 'name' at row 1

【问题讨论】:

  • 请附上您的实体代码,以便我们查看您是如何注释这些字段的。

标签: java mysql hibernate jdbc emoji


【解决方案1】:

我非常有信心,您清楚地表达了对您的整个技术堆栈使用 UTF-8 的意图……除了您的数据。

您真正的问题是您的数据(原始字符串)一开始就不是有效的 UTF-8。您可以使用以下 sn-p 轻松验证这一点:

public static boolean isValidUTF8(byte[] input) {
        CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
        try {
            utf8Decoder.decode(ByteBuffer.wrap(input));
            return true;
        } catch (CharacterCodingException e) {
            return false;
        }
    }

您应该一直使用utf8mb4(包括您的列定义,应该是... CHARSET=utf8mb4 COLLATE utf8mb4_general_ci 或... CHARACTER SET utf8mb4 COLLATE utf8mb4_bin)。

根据the documentation,您需要特别注意MySQL Connector的版本(和配置)。

【讨论】:

    【解决方案2】:

    我通过将 mysql-connector-java 升级到 5.1.49 并将以下内容添加到连接字符串来解决它

    {connection string}?characterEncoding=UTF-8&useUnicode=true
    

    参考:https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-charsets.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 2020-02-20
      • 2012-11-19
      • 2018-05-05
      • 2015-01-24
      • 2017-04-19
      相关资源
      最近更新 更多