当前位置: 首页 > 面试题库 >

如何在JdbcTemplate中使用PostgreSQL hstore / json

艾泰
2023-03-14
问题内容

有没有办法使用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

对于杰森

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(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();


 类似资料:
  • 我使用Spring初始化器、嵌入式Tomcat、Thymeleaf模板引擎和作为可执行JAR文件的包生成了一个Spring Boot web应用程序。 使用的技术: 错误:

  • 我想在使用application.properties的项目中使用2个或更多的jdbcTemplate。我尝试了,但遇到了运行时异常。 canNotGetJDBCConnectionException:未能获得JDBC连接;嵌套异常是java.sql.sqlException:无法为在org.springframework.JDBC.datasource.datasourceUtils.getCo

  • 29.2 使用JdbcTemplate Spring的JdbcTemplate和NamedParameterJdbcTemplate类是自动配置的,您可以将它们直接@Autowire到您自己的bean中: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.co

  • 我在向Postgresql表中插入整数数组时遇到问题,我该怎么做? 其中ball Numbers和ball NumbersMegaBall是ArrayList。用两位数填充。 以下是PostgreSQL表: 这是来自Springboot的错误: 出现意外错误(类型=内部服务器错误,状态=500)。PreparedStatementCallback;错误的SQL语法[INSERT in draw_r

  • 我有一个返回列表的现有服务 我如何将下面的示例转换为通量,这样我的结果就可以流式传输,而不必在内存中聚集所有项目? 第一个问题:这里我首先将第一个查询的所有结果提取到内存中,然后在内存中迭代并形成我所有的,然后返回整个列表。 因此我试图返回

  • 我正在使用jdbcTemplate将数据写入我的Oracle DB。我希望在两个不同的环境中重用同一个表的代码,而这两个环境之间的区别只是少了一列。所以在写数据之前,我需要检查列是否存在,以使用正确的sql查询,否则我会得到一个异常。所以我想要一些类似的东西: