6

I need to convert between a Map and a JSON string when communicating between a Java application and MySql. I've come across two very promising solutions: AttributeConverter and UserType.

Is there any pros/cons between choosing one solution over another? With all things considered equal, AttributeConverter sure does seem a lot simpler.

2 Answers 2

15

AttributeConverter requires JPA 2.1 (Hibernate 4.3+), but if it's available, it's a much cleaner choice. A custom UserType may break with future versions of Hibernate, while an AttributeConverter likely won't.

Make sure that you specify the @Convert annotation on the specific fields that you want to convert, rather than setting autoApply, since you don't want to convert all Maps or all Strings.

Also make sure that you use a library for the Map-String conversion, rather than hand-coding it.

Sign up to request clarification or add additional context in comments.

1 Comment

For those who are not clear what library to use, Jackson is pretty simple in this case.
2

As far as comparing these approaches goes, most of the time, AttributeConverters are generalley a cleaner solution.

Othe than the JPA version difference, there is another big downside/difference that deserves noticing: @Convert and @Id attributes don't work together (you'll get deserialization errors). If you need such functionality, you'll have to resort to UserTypes.

2 Comments

Thanks for the note on @Id and @Convert together, it helped a lot.
The JPA specification explicitly states that AttributeConverter should not be used to convert Id attributes, version attributes, relationship attributes, or attributes explicitly denoted as Enumerated or Temporal

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.