kennyg
kennyg

Reputation: 1059

AttributeConverter vs UserType for Hibernate

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.

Upvotes: 6

Views: 4407

Answers (2)

acdcjunior
acdcjunior

Reputation: 135792

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.

Upvotes: 0

ThrawnCA
ThrawnCA

Reputation: 1081

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.

Upvotes: 15

Related Questions