how to write chinese caracters into mysql with hibernate?

Viewed 608

im making a web application with javascript. Im using java servlet wich is connected with mysql database with hibernate. in Servlet there is a String in chinese, and when i try to write that strin into mysql field it shows up as "?" in mysql. my whole project in netbeans is set to charset=UTF-8. I tried to set collation and charset in database to utf-8, utf8mb4, big5 and none of them works. i also tried to change my column from varchar to nvarchar but when i click apply (mysql workbench) the column is still "varchar".

this is my servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        String tabla=request.getParameter("tabla");
        //String tabla contains chinese caracters
        String user=request.getParameter("user");
        Configuration myConf = new Configuration();
        myConf.configure("hib/hibernate.cfg.xml");
        StandardServiceRegistry service = new StandardServiceRegistryBuilder().
                applySettings(myConf.getProperties()).build();
        SessionFactory myFactory = myConf.buildSessionFactory(service);
        Session conn = myFactory.openSession();
        Transaction t = conn.beginTransaction();

        List<User>upislista;
        upislista=conn.createQuery("SELECT u FROM User u WHERE useUsername='"+user+"'").list();
        upislista.get(0).setUseKineski(tabla);





        t.commit();
        conn.close();
2 Answers

Hibernate XML:

<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>

Connection url:

db.url=jdbc:mysql://localhost:3306/db_nameuseUnicode=true&character_set_server=utf8mb4

The above changes were enough for me to upgrade from utf8 to utf8mb4 charset scheme.

As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.

Spring/Hibernate filter:

<form accept-charset="UTF-8">

Spring/Hibernate:

<property name="url" value="jdbc:mysql://localhost:3306/miniprojetjee?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8&characterEncoding=utf-8"/> (or maybe it is =yes)

"Spring":

@RequestMapping(value = "/getRegion2", produces={"application/json; charset=UTF-8"},method = RequestMethod.GET)

不知道你用的哪个版本的mysql, 但是你需要配置mysql

character_set_server=utf8mb4

一些版本hibernate能够正确配置,但是一些版本需要你手动配置。

Related