filmov
tv
Insert JSON to Postgres via Spring Data JPA using Java

Показать описание
Often, we come across scenarios where we store JSON objects in Relational databases, especially if you are using PostgreSQL, it comes with a built-in data types that support storing such objects called JSONB and JSON. Let us dive into what changes one needs to make to interact properly with columns of such type via JPA.
Prerequisite
The scope of this article is to show you how to configure your JPA Entity and Services to support JSONB or JSON columns in PostgreSQL. It is assumed that you already have setup your SpringBoot project with JPA configured.
Create a JSONB column in your table
Below shown is the bare minimum DDL query you need to run in your DB, to create a column of type JSONB
CREATE TABLE example_table (
id VARCHAR(100) PRIMARY KEY,
data JSONB NOT NULL,
);
;
Defining the JPA Entity
Below show a very simple Entity that supports a JSONB column, please refer to the comments made to understand each line of code:
@Entity
@Table(name = "example_table")
public class ExampleTable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private String id;
@Column(columnDefinition = "jsonb")
@ColumnTransformer(write = "?::jsonb")
private JsonNode data;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public JsonNode getData() {
return data;
}
public void setData(JsonNode Data) {
}
public NxDocumentDetails(String Id, JsonNode data) {
super();
this.Id = Id;
}
}
#java #postgres #backend #springboot #api