Aymer Aymer - 1 year ago 465
Java Question

How to use PostgreSQL hstore/json with jdbctemplate

Is there a way to use PostgreSQL json/hstore with jdbctemplate? esp query support.

for eg:


INSERT INTO hstore_test (data) VALUES ('"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"')

SELECT data -> 'key4' FROM hstore_test
SELECT item_id, (each(data)).* FROM hstore_test WHERE item_id = 2

for Json

insert into jtest (data) values ('{"k1": 1, "k2": "two"}');
select * from jtest where data ->> 'k2' = 'two';

Answer Source

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<String, String> hstoreMap = new HashMap<>();
hstoreMap.put("key1", "value1");
hstoreMap.put("key2", "value2");

PGobject jsonbObj = new PGobject();
jsonbObj.setValue("{\"key\" : \"value\"}");

use one of the following way to insert them to PostgreSQL:


jdbcTemplate.update(conn -> {
     PreparedStatement ps = conn.prepareStatement( "INSERT INTO table (hstore_col, jsonb_col)" );
     ps.setObject( 1, hstoreMap );
     ps.setObject( 2, jsonbObj );


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<String, String>) rs.getObject( "hstore_col" ));
((PGobject) rs.getObject("jsonb_col")).getValue();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download