如何使用PostgreSQL hstore/json和JdbcTemplate

Aym*_*mer 13 java postgresql spring 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
Run Code Online (Sandbox Code Playgroud)

为Json

insert into jtest (data) values ('{"k1": 1, "k2": "two"}');
select * from jtest where data ->> 'k2' = 'two';
Run Code Online (Sandbox Code Playgroud)

soj*_*jin 23

虽然答案很晚(对于插入部分),但我希望它对其他人有用:

获取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\"}");
Run Code Online (Sandbox Code Playgroud)

使用以下方法之一将它们插入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 );
});
Run Code Online (Sandbox Code Playgroud)

2)

jdbcTemplate.update("INSERT INTO table (hstore_col, jsonb_col) VALUES(?,?)", 
new Object[]{ hstoreMap, jsonbObj }, new int[]{Types.OTHER, Types.OTHER});
Run Code Online (Sandbox Code Playgroud)

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 );
Run Code Online (Sandbox Code Playgroud)

并获得价值:

(Map<String, String>) rs.getObject( "hstore_col" ));
((PGobject) rs.getObject("jsonb_col")).getValue();
Run Code Online (Sandbox Code Playgroud)


Vla*_*cea 5

甚至比 更容易JdbcTemplate,您可以使用Hibernate Types开源项目来保留 HStore 属性。

首先,您需要 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后,假设您有以下Book实体:

@Entity(name = "Book")
@Table(name = "book")
@TypeDef(name = "hstore", typeClass = PostgreSQLHStoreType.class)
public static class Book {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @NaturalId
    @Column(length = 15)
    private String isbn;
 
    @Type(type = "hstore")
    @Column(columnDefinition = "hstore")
    private Map<String, String> properties = new HashMap<>();
 
    //Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们使用注释properties对实体属性进行了注释@Type,并指定了hstore之前定义的类型@TypeDef以使用PostgreSQLHStoreType自定义 Hibernate 类型。

现在,当存储以下Book实体时:

Book book = new Book();
 
book.setIsbn("978-9730228236");
book.getProperties().put("title", "High-Performance Java Persistence");
book.getProperties().put("author", "Vlad Mihalcea");
book.getProperties().put("publisher", "Amazon");
book.getProperties().put("price", "$44.95");
 
entityManager.persist(book);
Run Code Online (Sandbox Code Playgroud)

Hibernate执行以下SQL INSERT语句:

INSERT INTO book (isbn, properties, id)
VALUES (
    '978-9730228236',
    '"author"=>"Vlad Mihalcea",
     "price"=>"$44.95", "publisher"=>"Amazon",
     "title"=>"High-Performance Java Persistence"',
    1
)
Run Code Online (Sandbox Code Playgroud)

而且,当我们获取Book实体时,我们可以看到所有属性都已正确获取:

Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load("978-9730228236");
 
assertEquals(
    "High-Performance Java Persistence",
    book.getProperties().get("title")
);

assertEquals(
    "Vlad Mihalcea",
    book.getProperties().get("author")
);
Run Code Online (Sandbox Code Playgroud)