问题
I have the following domain object:
@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;
}
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
);
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.
Right now any operation complains that the fields on Person
don't have a corresponding column in the table.
回答1:
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 it's better to use concrete object instead of String
here, like this:
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb", nullable = false)
private SomeObject json;
More info: 1, 2
来源:https://stackoverflow.com/questions/49836749/storing-entire-object-as-json-in-spring-data