Tips for persisting a JSON Object in PostgreSQL with Hibernate in Java

Looking for a way to save a JSON object in PostgreSQL database using Hibernate with Java. Although PostgreSQL offers json and jsonb data types, Hibernate doesn't have built-in mapping for these data types. Seeking guidance on how to proceed, I came across resources like "Persist a JSON Object Using Hibernate" and Custom Types in Hibernate and the @Type Annotation.

If you're also facing this challenge, check out and for more information.

As a newcomer to Hibernate, unsure if these are the right solutions or if there's an existing mapping for JSON data that I'm unaware of. Any guidance on the correct approach would be greatly appreciated. Thank you!

Answer №1

Sure, you'll need a custom Hibernate Type for this task. But don't worry about creating one yourself because Vlad Mihalcea has already done it for you! You can find it here. I personally use it as well.

Adding Maven Dependency

To begin, 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>

Mapping JPA Entity

Next, 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 all there is to it!

Answer №2

Setting up a table in postgres

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

Crafting a hibernate entity class named DemoJsonEntity with @TypeDefs

@Entity
@Table(name = "demoJson")
@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class)
    ,
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class DemoJsonEntity 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;
    }

}

Simple as that. All I needed was this dependency

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

For testing purposes, I attempted to save data like this

public static void main(String arg[]) {
    try {
        DemoJsonEntity obj = new DemoJsonEntity();
        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

https://i.stack.imgur.com/Uzkv6.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform a Pandas DataFrame into a unique custom nested JSON format

I am currently exploring Pandas and attempting to transform a Pandas DataFrame into a personalized nested JSON string (possibly saving it to a file). Although I initially utilized the built-in Pandas to_json() function, it did not yield the desired outco ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

When using Angular's ng-repeat with a JSON data source retrieved through $http AJAX, the resulting list

My goal is to showcase a list of elements by name and id using ng-repeat from a JSON file with a very basic AJAX request. var form = $("#loadAllServiceEngineForm"); var url = form.attr("action"); var App = angular.module('AdamApp', ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

Intent not reachable within AsyncTask context

Apologies for my poor English, but I have encountered an error with the AsyncTask class. When calling intent from PostExecute method in Main_Activity, I am getting a "Not Enclosing Instance type is accessible in scope" error. package com.example.pfc; im ...

Configuring Next.js with Next-Auth, Apollo, and GraphQL

Seeking advice on navigating a next.js front end using Apollo and GraphQL to connect with a PostgreSQL database. Initially, I separated the front and back ends assuming it would be beneficial, but now facing some tradeoffs. Next.js and NextAuth.js seem opt ...

Steps for accessing a specific key value from a hashmap with a freemarker template

In the code below, I am setting key values into a hashmap within the main function. How can I format the freemarker template to only read one specific key value instead of iterating through the entire list? import freemarker.template.TemplateException; ...

Tips for converting a JSON Array into a Java HashMap by using a specific field as a key with the help of GSON

Consider this scenario, with the following JSON data: [ {"id":"3", "location":"NewYork", "date":"yesterday"}, {"id":"4", "location":"Moscow", "date":"today"} ] After processing, we get a HashMap like this: <"3", POJOLocation("NewYork", "yesterday")&g ...

Transmit the data.json file to a node.js server using Postman

Hi there, I have a file named data.json saved on my desktop that I want to send to a node.js function. The contents of my data.json file are structured as follows: [{"key":"value"}, {same key value structure for 8000 entries}] This fil ...

Retrieve data with remote JSON to enable autocomplete functionality

I am experiencing some difficulties with the .autocomplete function. Here is my current code: <script type="text/javascript"> $( ".search" ).autocomplete({ source: [{label:'link label1', searchLink:'http://link1.com'}, ...

What is the best Haskell library for handling JSON data?

With approximately twelve JSON packages available on Hackage for Haskell, how can I determine which one is the best fit for my needs? Is there a way to gauge popular opinion on these packages? Is there any data available regarding the usage and popularity ...

Error message encountered: "TypeError with jQuery autocomplete and ajax

I can't seem to figure out why I keep encountering this error when trying to set up autocomplete with ajax source. "Uncaught TypeError: Cannot read property 'length' of undefined" Below is the route I have in express. exports.findAllIrds ...

Error message appeared while running Selenium WebDriver on Eclipse: "Selenium WebDriver runtime

An error occurred in the main thread: java.lang.IllegalStateException: The driver executable does not exist at location E:\chromedriver.exe. This issue is caused by the absence of the necessary driver executable file, which is r ...

What is the process for declaring a complex type within an Avro Schema?

After extensively studying the Avro documentation and various online examples (along with similar questions on StackOverflow), I tried to create an Avro schema. However, I had to remove fields one by one to identify the issue since the error message from t ...

What is the best method for converting a complex JSON structure, including arrays, integers, dictionaries, strings, and null values, into a pandas

I have the following JSON structure, { 'total_numbers': 2, 'data':[ { 'col3':'2', 'col4':[ { 'col5':'P', 'col ...

Converting a JSON object into a text format

Seeking advice on a web application I'm developing where a REST service is receiving a JSON string. The JSON string structure is as follows: { "string" : "value", "string" : "value", "object" : { "string" : "value", ...

Tips on how to Parse Multiple Json Files in Java

When I use the code provided below, I receive {"User_id":"test123","Password":"test225"}{"User_id":"test122","Password":"asds"} a JSON format that is considered invalid. What I actually want is the following JSON format but am having trouble creating it ...

Complete tile design displayed within a single tile in case of ajax failure

Uncertain about the adequacy of my title, but here is my problem: I have a tiles layout with a header, body, and footer. I utilize ajax requests to fetch data from the server and populate it on JSP using jQuery. On the server side (using Spring 3.1.2), I ...

Using Selenium with Java allows for the seamless passing of a Browser instance to another method

Currently, I am in the process of automating a web task using Selenium and Java. As a beginner in both Java and Selenium, I have encountered an issue with passing a Browser instance to a called method. My main method opens a webpage, performs some tasks on ...