Is there a way to use PostgreSQL json/hstore with JdbcTemplate
? esp query support.
for eg:
hstore:
INSERT INTO hstore_test (data) V
Although quite late for an answer (for the insert part), I hope it might be useful someone else:
Take the key/value pairs in a HashMap:
Map hstoreMap = new HashMap<>();
hstoreMap.put("key1", "value1");
hstoreMap.put("key2", "value2");
PGobject jsonbObj = new PGobject();
jsonbObj.setType("json");
jsonbObj.setValue("{\"key\" : \"value\"}");
use one of the following way to insert them to PostgreSQL:
1)
jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement( "INSERT INTO table (hstore_col, jsonb_col) VALUES (?, ?)" );
ps.setObject( 1, hstoreMap );
ps.setObject( 2, jsonbObj );
});
2)
jdbcTemplate.update("INSERT INTO table (hstore_col, jsonb_col) VALUES(?,?)",
new Object[]{ hstoreMap, jsonbObj }, new int[]{Types.OTHER, Types.OTHER});
3) Set hstoreMap/jsonbObj in the POJO (hstoreCol of type Map and jsonbObjCol is of type PGObject)
BeanPropertySqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource( POJO );
sqlParameterSource.registerSqlType( "hstore_col", Types.OTHER );
sqlParameterSource.registerSqlType( "jsonb_col", Types.OTHER );
namedJdbcTemplate.update( "INSERT INTO table (hstore_col, jsonb_col) VALUES (:hstoreCol, :jsonbObjCol)", sqlParameterSource );
And to get the value:
(Map) rs.getObject( "hstore_col" ));
((PGobject) rs.getObject("jsonb_col")).getValue();