4

Is it possible to insert json into a postgresql json column using the NamedParameterJDBCTemplate class in SpringFramework and I am getting a PSQLException: No hstore extension installed. From this I gather that the NamedParameterJDBCTemplateis trying to store the value as hstore.

Is there a way I can tell the NamedParameterJDBCTemplate to insert the value into the query as json?

The value is stored in java as a Map<String, String>

2 Answers 2

10

This works for me to insert Map as jsonb using namedjdbctemplate.

  1. Create json_string from Map using jackson library or GSON can be used.
  2. Create PGObject and fill with value like below.
  3. Use the PGObject in your SQL prepare statement.

Hope this helps.

ObjectMapper objectMapper = new ObjectMapper();
PGobject jsonObject = new PGobject();
String Map_Json_String = objectMapper.writeValueAsString(your_map);
jsonObject.setType("jsonb");
jsonObject.setValue(Map_Json_String);

String final insertSql = "INSERT INTO \"Table_Name\""
            + " VALUES (:jsonObject);";
Sign up to request clarification or add additional context in comments.

Comments

1

Put STRING, cast to JSONB, in sql

Add ::JSONB suffix to your SQL parameter.

Set the formatted string value, not a Map:

jdbcTemplate.update(""
    + "INSERT INTO my_table              "
    + "        (my_jsonb_column)         "
    + " VALUES (:my_jsonb_column::JSONB) ",

    Map.of("my_jsonb_column", "{\"my_key\": \"my value!\"}"));

In Spring

In Spring "you" usually convert "your" HashMaps to (json) strings using ObjectMapper:

    Map.of("my_jsonb_column", objectMapper.writeValueAsString(yourMap))

NOTE: Posgres' JsonB only supports Bool, Number, and Text values. So convert nested objects, if any, to string recursively.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.