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

2022-09-02 19:54:41

有没有办法将PostgreSQL json/hstore与?esp 查询支持。JdbcTemplate

例如:

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';

答案 1

虽然对于答案(对于插入部分)来说已经很晚了,但我希望它可能对其他人有用:

取哈希图中的键/值对:

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

答案 2

甚至比 更简单,您可以使用休眠类型开源项目来持久保存 HStore 属性。JdbcTemplate

首先,您需要 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

然后,假设您具有以下实体: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
}

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

现在,在存储以下实体时: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);

休眠执行以下 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
)

而且,当我们获取实体时,我们可以看到所有属性都已正确获取: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")
);

推荐