Hibernate + MySQL: How to set the encoding utf-8 for database and tables

后端 未结 9 2177
故里飘歌
故里飘歌 2020-12-13 00:34

My system runs on Linux Mandriva, RDBMS - MySQL 5. I need to have the database and tables created in UTF-8.

Here i

相关标签:
9条回答
  • 2020-12-13 01:26

    how about change database collation?

    ALTER DATABASE [database] CHARACTER SET utf8 COLLATE utf8_unicode_ci;

    0 讨论(0)
  • 2020-12-13 01:30

    How to change the encoding to UTF-8?

    I used a local dialect class that extended the MySQLDialect and changed the table-type string:

    public class LocalMysqlDialect extends MySQLDialect {
        @Override
        public String getTableTypeString() {
            return " DEFAULT CHARSET=utf8";
        }
    }
    

    I was actually extending the MySQL5InnoDBDialect type so I was really using:

    public class LocalMysqlDialect extends MySQL5InnoDBDialect {
        @Override
        public String getTableTypeString() {
            return " ENGINE=InnoDB DEFAULT CHARSET=utf8";
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:37

    First of all on Java side you should specify UTF-8 instead of utf8, refer to table here.

    Second, characterEncoding is not a character set your tables will be created in, this is just a charset that will be used while communication and reading/writing data to/from database.

    MySQL Docs say that during the creation of tables, a DB charset will be used if nothing was specified in these regards. Which means that in order to make this possible, your database (not MySQL Server) should be created like that:

    create database DB_NAME character set utf8;

    Afterwards your tables in this database should be created in utf8 encoding. Same story with collation.

    But of course you shouldn't rely on Hibernate's hbm2ddl, read here for more details.

    0 讨论(0)
提交回复
热议问题