How to automatically serialize and deserialize JSON string using JPA and Hibernate?

Viewed 20546

I have data class/table "User" that has column "preferences"

CREATE table "user"; 
ALTER TABLE "user" ADD COLUMN preferences TEXT;

Preferences type is TEXT and I am storing JSON there.

public class User extends AbstractEntity{
public String preferences;
}

so user.preferences value is "{notifyByEmail:1, favouriteColor:"blue" }"

How can I wrap it with some annotation so I can access it like

user.preferences.notifyByEmail

or without need to wrap into data object

user.preferences.get("notifByEmail");
user.preferences.set("notifByEmail",true);

I imagine there could be some Jackson annotation that I can add to field like

@JsonGenerate
public String preferences;

I am fairly new to JPA and documentation is steep.

I believe my case is quite common. Can anyone give any examples?

4 Answers

It's very easy to persist JSON objects using Hibernate.

You don’t have to create all these types manually, you can simply get them via Maven Central using the following dependency:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version> 
</dependency> 

For more info, check out the Hibernate Types open-source project.

Now, you need to add this @TypeDef annotation on the class level or in a package-info.java package-level descriptor to use the JsonType Hibernate Type:

@TypeDef(
    name = "json",
    typeClass = JsonType.class
)

And the entity mapping will look like this:

@Type(type = "json")
@Column(columnDefinition = "jsonb")
private String preferences;

That's it!

Related