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 );
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, "") }
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)
Top comments (1)
This was a very useful article, which I had not been surprised to find out about before!