2014-01-27 43 views
11

有没有办法在jdbctemplate中使用PostgreSQL json/hstore? esp查询支持。如何在jdbctemplate中使用PostgreSQL hstore/json

为如:

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'; 

回答

17

虽然很晚的答案(用于插入的部分),我希望这可能是有用别人:

取一个HashMap中的键/值对:

Map<String, String> 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) 集hstoreMap/jsonbObj在POJO (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<String, String>) rs.getObject("hstore_col")); 
((PGobject) rs.getObject("jsonb_col")).getValue(); 
+0

奇怪的是,它仍然没有为我工作。升级到最新的postgres版本驱动程序修复了这个问题。 – linqu

相关问题