I am trying to store some generic changable object in postgres/any database using spring boot. is this possible to store those objects without any use of pojo/entity class?
1 Answer
There are several ways within the SpringBoot ecosystem to do what you are describing, but the most basic would be using JdbcTemplate
Starting with a table that looks like this
create table foo (bar jsonb);
with one inserted json object:
insert into foo values ('{ "firstName": "Aurthur", "lastName": "Dent" }');
An method with a Spring-injected datasource would look something like this:
@Component
public class JsonbExample {
@Autowired DataSource dataSource;
public void fetchJsonField() {
var jdbcTemplate = new JdbcTemplate(dataSource);
List<JsonNode> nodeList = jdbcTemplate.query("select bar from foo", (RowMapper<JsonNode>) (rs, rowNum) -> {
try {
var obj = rs.getObject("bar", PGobject.class);
return new ObjectMapper().readValue(obj.getValue(), JsonNode.class);
} catch (JsonProcessingException e) {
log.error(e);
return null;
}
});
System.out.println(nodeList);
}
The output will be
[{"lastName":"Dent","firstName":"Aurthur"}]
Notice that the column defined as postgres type jsonb gets returned as type PGObject
io.r2dbc.postgresql.codec.Jsonclass which you can use as a generic container for postgres'sjsonandjsonbtypes (r2dbc knows how to convert from pg-json(b) to r2dbc json).