java - 如何将 PostgreSQL hstore/json 与 JdbcTemplate 一起使用

标签 java spring postgresql jdbctemplate hstore

有没有办法将 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<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) 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) 在POJO中设置hstoreMap/jsonbObj(hstoreCol为Map类型,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 );

并获得值(value):

(Map<String, String>) rs.getObject( "hstore_col" ));
((PGobject) rs.getObject("jsonb_col")).getValue();

关于java - 如何将 PostgreSQL hstore/json 与 JdbcTemplate 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21383457/

相关文章:

java - Java程序的内存区域?

java - 我需要在Java上将41.32万亿放入一个变量中,但是long数据类型仅限于4万亿

java - 如何为用户的 Activity 设置计时器?

java - Spring Framework 在 JBoss 上看不到 cglib

java - java实现Memcache的错误

java - 无法理解Java中super的功能

java - Spring 不断返回 String 作为响应而不是 Html

java - 如何让 hibernate 模式仅在表不存在时才创建表?

sql - PostgreSQL 可以返回一个值列表,其中后面的值会覆盖前面的值吗?

sql - Postgres递归查询在遍历parent_id时更新字段的值