如何使用PostgreSQL hstore / json和jdbctemplate
有没有办法使用PostgreSQL json / hstore和jdbctemplate? esp查询支持。
例如:
hstore:
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
为Json
insert into jtest (data) values ('{"k1": 1, "k2": "two"}'); select * from jtest where data ->> 'k2' = 'two';
虽然答案很晚(对于插入部分),但我希望它对其他人有用:
获取HashMap中的键/值对:
Map hstoreMap = new HashMap<>(); hstoreMap.put("key1", "value1"); hstoreMap.put("key2", "value2"); PGobject jsonbObj = new PGobject(); jsonbObj.setType("json"); jsonbObj.setValue("{\"key\" : \"value\"}");
使用以下方法之一将它们插入PostgreSQL:
1)
jdbcTemplate.update(conn -> { PreparedStatement ps = conn.prepareStatement( "INSERT INTO table (hstore_col, jsonb_col)" ); 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)在POJO中设置hstoreMap / jsonbObj(Map类型为hstoreCol,jsonbObjCol类型为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 );
并获得价值:
(Map) rs.getObject( "hstore_col" )); ((PGobject) rs.getObject("jsonb_col")).getValue();