【发布时间】:2016-08-10 10:54:32
【问题描述】:
我对Mysql的字符编码感到困惑。 我像这样在 Hibernate 中配置 connection.url:
<property name="connection.url">jdbc:mysql://localhost:3306/Bag</property>
<property name="hbm2ddl.auto">update</property>
实体类是:
@Entity
@Table(name = "notification")
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "username", unique = true,nullable = false, length = 64)
private String username;
@Column(name = "title", nullable = false, length = 64)
private String title;
@Column(name = "message", nullable = false, length = 1000)
private String message;
@Column(name = "uri", nullable = true, length = 256)
private String uri;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
我在 mysql 中创建了一个名为“通知”的表:
notification | CREATE TABLE `notification` (
`id` bigint(20) NOT NULL,
`message` longtext NOT NULL,
`title` varchar(64) NOT NULL,
`uri` longtext,
`username` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
当我插入中文字符串时,它不能正常工作:
mysql> select * from notification;
+----+---------------------------------+--------------------+------+
| id | message | title | uri |username |
+----+---------------------------------+--------------------+--------
| 1 | ??,???????? | ???? |/post/toPluto | pluto |
我已经通过将 connection.url 更改为:
<property name="connection.url">jdbc:mysql://localhost:3306/Bag?useUnicode=true&characterEncoding=UTF-8</property>
但我不知道原因,谁能告诉我原因?
这是 mysql 字符集
Variable_name Value
| character_set_client | utf8
|
| character_set_connection | utf8
|
| character_set_database | utf8
| character_set_filesystem | binary
|
| character_set_results | utf8
|
| character_set_server | latin1
|
| character_set_system | utf8
|
| character_sets_dir | /usr/local/mysql-5.7.11-
osx10.9x86_64/share/charsets/ |
这是中文字符串的十六进制:
mysql> select hex(message) from notification;
+----------------------------------------------------------------+
| hex(message) |
+----------------------------------------------------------------+
| 3F3F2C3F3F3F3F3F3F3F3F
【问题讨论】: