【问题标题】:Writing UTF-8 to BLOB in MariaDB and in MySQL using Hibernate 4使用 Hibernate 4 在 MariaDB 和 MySQL 中将 UTF-8 写入 BLOB
【发布时间】:2018-01-03 03:31:15
【问题描述】:

我有一个带有如下表的数据库:

CREATE DATABASE `test_db` /*!40100 DEFAULT CHARACTER SET utf8 */;

CREATE TABLE `atable` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `shortText` varchar(255) DEFAULT NULL,
  `longText` blob,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

存在于 MySQL (5.7.18-0ubuntu0.16.04.1) 和 MariaDB (10.1.23-MariaDB) 服务器上。我正在用 Hibernate 从我的 Java 应用程序中写一个 UTF-8 数据。实体对象如下:

@Entity(name = "atable")
public class AClass{
  @Id
  @Column(name = "id", unique = true)
  @GeneratedValue
  Long id;
  @Column
  private String shortText; //also exists setter and getter, of course
  private byte[] longText;    
  public void setLongText(String s){this.longText = (s!=null)?s.getBytes():null;}
  public String getLongText(){return this.longText!=null?new String(longText):null;}
}

对于这两个数据库,我都使用 JDBC 连接 url:

jdbc:mysql://localhost:3306/app_db?useUnicode=true&characterEncoding=utf8

当我将 UTF-8 数据写入 MySQL 时,它工作正常。

但是当我将它写入 MariaDB 时,它只将 UTF-8 存储到 varchar,但到 blob 它写入 ???? 而不是我的数据。甚至要求: select hex(longText) from atable where id=0; 显示 MariaDB 在那里用代码 3F 写符号而不是我的字母。

什么是wearg,我能用它做什么?

【问题讨论】:

  • BLOB 首字母缩写词中的“B”表示字节或二进制。字段可以保存字节(二进制)等价的数据,你不能假设是文本
  • @JacekCz,正如你在实体类中看到的那样,我将字节数组存储在那里

标签: java mysql hibernate jdbc mariadb


【解决方案1】:

s.getBytes()保证将文本编码为 UTF-8。 new String(longText)保证将字节解码为 UTF-8。

这两种方法都使用系统的默认字符集,在 Windows 系统上不是 UTF-8。

为保证正确操作,请指定字符集:

s.getBytes(StandardCharsets.UTF_8)
new String(longText, StandardCharsets.UTF_8)

【讨论】:

    【解决方案2】:

    http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored 中讨论了多个“问号”及其原因

    如果您遇到的问题多于涵盖范围,请提供连接参数和其他提及的内容。

    对于表情符号和中文,您需要将列/表设为utf8mb4,而不仅仅是utf8

    【讨论】:

    • 我认为尝试使用“抢先式”UTF-8 编码并将字节存储为 BLOB(而不是将字符串存储为 CLOB)可能是为了避免整个utf8/utf8mb4 问题。尽管如此,它对我来说还是很难闻。
    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 2014-12-11
    • 1970-01-01
    • 2017-01-24
    • 2015-02-13
    • 2012-06-24
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多