Is there a way to use PostgreSQL json/hstore with JdbcTemplate
? esp query support.
for eg:
hstore:
INSERT INTO hstore_test (data) V
Even easier than JdbcTemplate
, you can use the Hibernate Types open-source project to persist HStore properties.
First, you need the Maven dependency:
com.vladmihalcea
hibernate-types-52
${hibernate-types.version}
Then, assuming you have the following Book
entity:
@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 properties = new HashMap<>();
//Getters and setters omitted for brevity
}
Notice that we annotated the properties
entity attribute with the @Type
annotation and we specified the hstore
type that was previously defined via @TypeDef
to use the PostgreSQLHStoreType custom Hibernate Type.
Now, when storing the following Book
entity:
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);
Hibernate executes the following SQL INSERT statement:
INSERT INTO book (isbn, properties, id)
VALUES (
'978-9730228236',
'"author"=>"Vlad Mihalcea",
"price"=>"$44.95", "publisher"=>"Amazon",
"title"=>"High-Performance Java Persistence"',
1
)
And, when we fetch the Book
entity, we can see that all properties are fetched properly:
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")
);