3

I have a json object in java and I want to save that Object in PostgreSQL database using hibernate.

I checked PostgreSQL it provides json and jsonb datatypes.

But hibernate doesn't provide mapping to these dataTypes and I am stuck, how to go about it.

I looked quite a bit and found "Persist a JSON Object Using Hibernate" or Custom Types in Hibernate and the @Type Annotation

https://www.baeldung.com/hibernate-persist-json-object

https://www.baeldung.com/hibernate-custom-types

but as I am quite new to hibernate I am not sure if these are what I need or hibernate does provide mapping for json data and I just don't know about it.

I hope someone can guide me, as what is the right way to do it? Thanks

2 Answers 2

3

Yes, you will need a custom Hibernate Type for it, but, instead of creating one yourself, Vlad Mihalcea already did it for you (At here). I am also using it.

Maven dependency

First, add the following dependency to your pom.xml file:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>2.10.4</version>
</dependency>

JPA entity mapping

Afterward, you can define a @TypeDef mapping to register the JSON type:

@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class),
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
@MappedSuperclass
public class BaseEntity {

}

@Entity
@Table(name = "foo")
public class Foo extends BaseEntity {


    @Type(type = "jsonb")
    @Column(name = "someJsonColumn")
    private Map<String, Object> someJsonField = Maps.newHashMap();


}

That's it!

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

5 Comments

So I don't need to follow this link here. thorben-janssen.com/…
I am so confused right now. Tried many things don't none seem to work. Can you please provide a working example. "A very simple example for you to kick-start :" I am so sorry but still unable to follow up.
what will go in this class
@MappedSuperclass public class BaseEntity { }
anything that are common to all the entities , for example its ID , createdBy, createdTime etc.
0

Create a table in postgres

CREATE TABLE demoJson(
    id SERIAL NOT NULL PRIMARY KEY,
    jsonData JSONB NOT NULL
);

I created a hibernate entity class as DemoJsonEnitity and defined @TypeDefs

@Entity
@Table(name = "demoJson")
@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class)
    ,
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class DemoJsonEnitity implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id")
    private int dataId;

    @Type(type = "jsonb")
    @Column(name = "jsonData", columnDefinition = "jsonb")
    private String jsonData;

    public int getDataId() {
        return dataId;
    }

    public void setDataId(int dataId) {
        this.dataId = dataId;
    }

    public String getJsonData() {
        return jsonData;
    }

    public void setJsonData(String jsonData) {
        this.jsonData = jsonData;
    }

}

And thats it. So easy, I used this dependency

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>2.9.11</version>
</dependency>

To check I tried saving data as

public static void main(String arg[]) {
    try {
        DemoJsonEnitity obj = new DemoJsonEnitity();
        JSONObject jsonObj = new JSONObject();
        Map m1 = new LinkedHashMap(2);
        m1.put("oldValue", "Active");
        m1.put("newValue", "InActive");
        jsonObj.put("status", m1);
        Map m2 = new LinkedHashMap(2);
        m2.put("oldValue", "Test 6");
        m2.put("newValue", "Test 6 updated");
        jsonObj.put("taskDetails", m2);
        obj.setJsonData(jsonObj.toString());
        Session session = null;
        Transaction tx = null;
        try {
            session = sf.openSession();
            tx = session.beginTransaction();
            session.save(obj);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            throw new RuntimeException(e);
        } finally {
            session.close();
        }
    } catch (Exception e) {
        System.out.println("error: " + e.getMessage());
    }
}

Output

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.