Skip to content

Ferdinand Agyei-Yeboah

Inserting data into json column type in Spring

March 22, 2022

Using json type in postgres grants access to json data manipulation functions (ex: json_agg), but how do you insert data from an application perspective?

Option 1: Set stringtype=unspecified

This can be sent in the properties via database url or when creating the spring datasource.

jdbc:postgresql://<host>:<port>/<db-name>?stringtype=unspecified

OR

@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("driver");
dataSourceBuilder.url("url");
dataSourceBuilder.username("username");
dataSourceBuilder.password("password");
Properties props = new Properties();
props.setProperty("stringtype", "unspecified"); //this
dataSourceBuilder.properties(props);
return dataSourceBuilder.build();
}

Postgres jdbc driver docs (search stringtype) - link

Option 2: Use hibernate-types library

This article shows approach - link

Option 3: Roll your own by registering hibernate UserType

This article shows approach - link

Misc

Note: You can use Jackson’s JsonNode if you need to store json data but the json is free form. You will be able to store the JsonNode type into the database using the 1st, and 2nd options with minimal changes (no need to convert or anything).


Software Engineering Tutorials & Best Practices