5

UTF-8 with JPA and Glassfish 4.0

 3 years ago
source link: https://www.codesd.com/item/utf-8-with-jpa-and-glassfish-4-0.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

UTF-8 with JPA and Glassfish 4.0

advertisements

I am having difficulties with UTF-8 characters. This is a simple JSF project. I use JSF 2.2 and Glassfish 4.0

I have a method where I go:

em.persist(user);

When I debug

user.getName()

in this point, I can see the utf-8 characters in my IDE. Also I keep the string in a session - bean and I can see them on the browser fine as well.

Only when they are persisted to DB, they are persisted as: ?????

I can also edit the DB myself and save utf-8 characters. What I mean is, my SQL configuration is good for UTF-8.

The problem is somewhere in JPA.

This is what I have tried: ( all together: )

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="Persistence" transaction-type="JTA">
        <jta-data-source>fus</jta-data-source>
        <class>com.tugay.fup.core.model.User</class>
        <properties>
            <property name="javax.persistence.jdbc.url"
                  value="jdbc:mysql://localhost:3306/fus?useUnicode=yes&characterEncoding=UTF-8"/>
        </properties>
    </persistence-unit>
</persistence>

This is glassfish-web.xml:

<glassfish-web-app>
    <parameter-encoding default-charset="UTF-8"/>
</glassfish-web-app>

And I am using EntityManager managed by container (transaction type = JTA)

So in JDBC connection pools in Glassfish I have:

jdbc:mysql://localhost:3306/fus?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8

for: property: URL...

However none of these help.

Still characters not persisted correctly.


When using Glassfish, you can set these properties as additional to your JDBC Connection Pools. Locate and view your database connection in Web Administration (Resources->JDBC Connection Pools->your.connection). In additional properties tab add (if there are not present yet) mentioned properties and restart your server:

//name, value
characterEncoding, UTF-8
characterSetResults, UTF-8
useUnicode, true

The result will be the same if parameters are added to URL, but this is more maintainable solution in my opinion.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK