Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Hibernate 4在MariaDB和MySQL中将UTF-8写入BLOB_Java_Mysql_Hibernate_Jdbc_Mariadb - Fatal编程技术网

Java 使用Hibernate 4在MariaDB和MySQL中将UTF-8写入BLOB

Java 使用Hibernate 4在MariaDB和MySQL中将UTF-8写入BLOB,java,mysql,hibernate,jdbc,mariadb,Java,Mysql,Hibernate,Jdbc,Mariadb,我有一个数据库,其表如下: 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` (`

我有一个数据库,其表如下:

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
,它将
??
而不是我的数据。甚至要求:
从表中选择十六进制(longText),其中id=0
显示MariaDB在那里用代码3F而不是我的字母写符号

什么是worng?我能用它做什么?

s.getBytes()
不保证将文本编码为UTF-8<代码>新字符串(长文本)
不保证将字节解码为UTF-8

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

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

s.getBytes(StandardCharsets.UTF_8)
new String(longText, StandardCharsets.UTF_8)
本文讨论了多重“问号”及其原因

如果您有更多的问题,请提供连接参数和其他提到的内容


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

“B”在BLOB首字母缩写中表示字节或二进制。字段可以保存数据的字节(二进制)等价物,不能假定为text@JacekCz,正如您在entity类中看到的,我在那里存储的正是字节数组。我认为尝试使用“先发制人”UTF-8编码并将字节存储为BLOB(而不是仅将字符串存储为CLOB)可能是试图避免整个utf8/utf8mb4问题。尽管如此,我还是觉得很难闻。