Search code examples
javamysqlhibernateutf-8wildfly

Java EE, Hibernate, MySql UTF-8 query doesn't work


So I have set up hibernate with Wildfly and MySql.

Querying works, but have problem querying UTF-8 character names.

On MySql:

SELECT * FROM users WHERE firstname = "ნიკა";

Doesn't result in empty set.

While in java:

Session session = HibernateUtils.getSession();

String name = request.getParameter("name");

CriteriaBuilder builder = session.getCriteriaBuilder();

CriteriaQuery<UsersEntity> query = builder.createQuery(UsersEntity.class);
Root<UsersEntity> usersRoot = query.from(UsersEntity.class);
query.select(usersRoot)
        .where(builder.equal(usersRoot.get("firstname"), name));

List<UsersEntity> list = session.createQuery(query).list();

session.close();

writeUsers(list, response.getWriter());

Results in an empty set when querying localhost:8080/main?name=ნიკა

How do I fix this ?

UPDATE:

I also have issue that when querying all data and displaying them non english characters are replaced with question marks.

UPDATE 2:

This code results in showing up question marks on browser:

response.getWriter().write("ნიკა ჩხარტიშვილი");

While this one works properly:

response.setCharacterEncoding("UTF-8");
response.getWriter().write("ნიკა ჩხარტიშვილი");

When querying database with this query SELECT * FROM users WHERE username='ნიკა' database receives question marks instead of ნიკა (That's what shows up in wireshark).

I think it's wildfly issue because it received UTF-8 correctly but sends question marks unless it's specified to send UTF-8.


Solution

  • I fixed it.

    First connection to client wasn't UTF-8. Fixed it with:

    response.setCharacterEncoding("UTF-8");
    

    This works for one servlet though. Updated wildfly standalone.xml configuration file to

    <servlet-container name="default" default-encoding="UTF-8">
        <jsp-config/>
        <websockets/>
    </servlet-container>
    

    Added default-encoding property to servlet-container, now every response will have default UTF-8 encoding.

    JDBC Communication wasn't UTF-8.

    Fixed with updating connection.url, appended

    ?useUnicode=yes&amp;characterEncoding=UTF-8 at the end.

    <property name="connection.url">jdbc:mysql://localhost:3306/cnick?useUnicode=yes&amp;characterEncoding=UTF-8</property>
    

    When last time I did this I thought it didn't work because what I was querying wasn't in the database. Now it's working.