DEV Community

TaharaKanta
TaharaKanta

Posted on

1

Insert into a jsonb Column in Spring Boot 3 + JPA + PostgreSQL

Prerequisites

We will check the database tables for the given environment.

Environment

Spring Boot ver 3.3.1
gradle
kotlin
jdk 21
psql (PostgreSQL) 14.16

Database

CREATE TABLE IF NOT EXISTS SAMPLE_TABLE (
    id SERIAL PRIMARY KEY,
    json_data JSONB NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

Please ensure that Spring Boot is connected to the PostgreSQL server by inserting data into the database using tools such as psql, and confirm it using JPA's .findAll(), etc.

Sample Code

build.gradle.kts

Add the necessary dependencies

```kotlin name=build.gradle.kts
dependencies {
// Required for setting the jsonb type
// Adjust the version of hypersistence-utils-hibernate as needed for your environment
implementation "io.hypersistence:hypersistence-utils-hibernate-60:3.5.2"
}




## SampleEntity.kt



```kotlin name=SampleEntity.kt
import io.hypersistence.utils.hibernate.type.json.JsonType
import jakarta.persistence.*
import org.hibernate.annotations.Type

@Entity
@Table(name = "SAMPLE_TABLE")
data class SampleEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    val id: Long?,

    // Declaring @Type will convert the String to Json
    @Type(JsonType::class)
    // Specify jsonb with columnDefinition
    @Column(name = "json_data", columnDefinition = "jsonb")
    val jsonData: String
){
    // Add a no-argument constructor
    constructor() : this(null,  "")
}
Enter fullscreen mode Exit fullscreen mode

SampleRepository.kt

```kotlin name=SampleRepository.kt
import com.sample.SampleEntity
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface SampleRepository : JpaRepository




## SampleService.kt



```kotlin name=SampleService.kt
            val entity = SampleEntity(
                // Convert json to string before passing
                jsonData = "{\"name\":\"dummyName\"}"
            )
            val savedEntity = sampleEntityRepository.save(entity)
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
takuapp profile image
TakuyaHiraoka

This was a very useful article, which I had not been surprised to find out about before!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay