使用休眠将表情符号保存到 mysql 不正确的字符串值:第 1 行第 'name' 列的“\xF0\x9F\x98\x88\xF0\x9F...”

saving emoji to mysql using hibernate Incorrect string value: '\xF0\x9F\x98\x88\xF0\x9F...' for column 'name' at row 1

我的连接字符串具有以下属性 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

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

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

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 连接器版本(和配置)。

我通过将 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