将整个对象作为 json 存储在 Spring Data 中 [英] Storing entire object as json in Spring Data
问题描述
我有以下域对象:
@Data
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String first;
private String last;
private Integer age;
private String json;
}
和 PersonRepository 扩展 Repository
.我想要的是存储在一个看起来像这样的表中:
and a PersonRepository extends Repository<Person, Long>
. What I would like is to store in a table that looks like this:
CREATE TABLE IF NOT EXISTS person
(
id SERIAL NOT NULL PRIMARY KEY,
json JSONB NOT NULL
);
有没有办法覆盖 Spring Data 读写数据库的方式?理想情况下,我会使用 Jackson 将对象与 JSON 相互转换.
Is there a way to override the way Spring Data reads and writes to/from the database? Ideally I'd use Jackson to convert the object to/from JSON.
现在任何操作都会抱怨 Person
上的字段在表中没有相应的列.
Right now any operation complains that the fields on Person
don't have a corresponding column in the table.
推荐答案
您可以使用 hibernate-types 由 Vlad Mihalcea 提供的 lib - Hibernate 作者之一:
You can use hibernate-types lib by Vlad Mihalcea - one of Hibernate authors:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.1.1</version>
</dependency>
然后你可以像这样更新你的实体:
Then you can update your entity like this:
@Data
@Entity
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//...
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb", nullable = false)
private String json;
}
IMO 最好在这里使用具体对象而不是 String
,如下所示:
IMO it's better to use concrete object instead of String
here, like this:
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb", nullable = false)
private SomeObject json;
这篇关于将整个对象作为 json 存储在 Spring Data 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!