Storing entire object as json in Spring Data

非 Y 不嫁゛ 提交于 2020-01-06 06:50:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!