Medium article: / configuring-json-column-in-jpa-entity-in-j...
Subscribe to my free newsletter: / subscribe
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:
import org.hibernate.annotations.ColumnTransformer;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.persistence.*;
@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) {
this.json_spec = json_spec;
}
public NxDocumentDetails(String Id, JsonNode data) {
super();
this.Id = Id;
this.data = data;
}
}
#java #postgres #backend #springboot #api
In questa pagina del sito puoi guardare il video online Insert JSON to Postgres via Spring Data JPA using Java della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Friend of Tech 21 febbraio 2025, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 804 volte e gli è piaciuto 24 spettatori. Buona visione!