UTF-8 with Hibernate 3.0 and MySQL
Hi again, I’m now tackling something I’ve been meaning to do for ages (and probably should have done before I started the project) and that is to use Hibernate rather than rolling my own SQL.
I’m reading the book “Hibernate in Action” by Christian Bauer and Gavin King and have been trying it out. The book relates to Hibernate 2.0 and 2.1 so doesn’t include annotations which is a bit of a shame, but it’s still a good start.
Unfortunately as readers of this blog will know, I’m trying to put UTF-8 strings into the database so you can imagine my disappointment when I saw the familiar question marks appearing where there should be interesting new characters.
The fix turned out to be not so difficult to find however, thanks to Philip Whirlycott’s blog posting More UTF-8 head-thumping with Hibernate 3 (obviously I’m not the only one struggling with these issues).
With Hibernate 3 (maybe not with 2.1, I’m not sure), you need to add some extra connection parameters:
jdbc:mysql://localhost/mydb?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
If you put this in your hibernate.cfg.xml file for the JDBC URL it works and you can save the UTF-8 correctly.
Tags: Hibernate, Java, MySQL, Persistence
Subscribe to news from Isocra



Thanks for this useful post – I had the same problem and didn’t know what to do.
One update for using JPA: not all the parameters are needed and they cause an exception while hibernate tries to parse the persistence.xml file. For me, the following work fine (for hebrew):
<property name=”hibernate.connection.url” value=”jdbc:mysql://localhost/second_homes?characterEncoding=UTF-8″/>
jdbc:mysql://localhost/mydb?characterEncoding=UTF-8
Thanks a lot, you post where very helpfull
BISO
Thanks for your suggestion, I’ll use that with Grails.
[...] Gefunden auf: http://www.isocra.com/2007/01/utf-8-with-hibernate-30-and-mysql/ [...]
thanks a lot for your post …. i steel has this problem . i am using hibernate3 with spring and jdbc:mysql://localhost/mydb?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 dose not work 4 me please advice.
thanx for thiss usefull note.
but i still have a problem inserting persian characters
Hibernate: insert into Stocks (symbol, corpName, maxPrice, minPrice, lastPrice, finishedPrice, yesterdayPrice, changed, percent, bestRequest, bestOffer) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
765 [main] WARN org.hibernate.util.JDBCExceptionReporter – SQL Error: 1366, SQLState: HY000
765 [main] ERROR org.hibernate.util.JDBCExceptionReporter – Incorrect string value: ‘\xD8\xB4\xD8\xA7\xD8\xB1…’ for column ’symbol’
SOLVED!
i just had to drop the db and create it again with new unicode collation