2014-01-27 44 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

相關問題