Search code examples
jsonhibernatejpaormjackson

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


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?


Solution

  • Honestly I think your best solution is to create a separate table (preference) for your properties.

    +------------+
    | preference |
    +------------+---------+------+-----+
    | Field      | Type    | Null | Key |
    +------------+---------+------+-----+
    | user_id    | bigint  | NO   | PRI |
    | key        | varchar | NO   | PRI |
    | value      | varchar | NO   |     |
    +------------+---------+------+-----+
    

    You can map this in your entity like this:

    @Entity
    public class User
    {
        @Id
        private Long id;
    
        @ElementCollection
        @MapKeyColumn(name = "key")
        @Column(name = "value")
        @CollectionTable(name = "preference",
            joinColumns = @JoinColumn(name = "user_id"))
        private Map<String, String> preferences;
    }
    

    This way your database is more normalized and you don't have to fool around with 'creative solutions' like storing preferences as JSON.