How to use PostgreSQL hstore/json with JdbcTemplate

前端 未结 2 1268
借酒劲吻你
借酒劲吻你 2021-02-04 07:47

Is there a way to use PostgreSQL json/hstore with JdbcTemplate? esp query support.

for eg:

hstore:

INSERT INTO hstore_test (data) V         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 08:16

    Although quite late for an answer (for the insert part), I hope it might be useful someone else:

    Take the key/value pairs in a HashMap:

    Map hstoreMap = new HashMap<>();
    hstoreMap.put("key1", "value1");
    hstoreMap.put("key2", "value2");
    
    PGobject jsonbObj = new PGobject();
    jsonbObj.setType("json");
    jsonbObj.setValue("{\"key\" : \"value\"}");
    

    use one of the following way to insert them to 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) Set hstoreMap/jsonbObj in the POJO (hstoreCol of type Map and jsonbObjCol is of type 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 );
    

    And to get the value:

    (Map) rs.getObject( "hstore_col" ));
    ((PGobject) rs.getObject("jsonb_col")).getValue();
    

提交回复
热议问题