I use in application MySQL 5.7 and I have JSON columns. When I try running my integration tests don\'t work because the H2 database can\'t create the table. This is the erro
Example with Kotlin + Spring + Hibernate + Postgres + jsonb column
Create the entity:
@Entity
@TypeDef(name = "jsonb", typeClass = JsonBinaryType::class)
class MyEntity(
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
val myConfig: String,
@Id
@GeneratedValue
val id: Long = 0,
)
JsonBinaryType.class comes from https://github.com/vladmihalcea/hibernate-types
com.vladmihalcea
hibernate-types-52
2.9.13
Configure your H2 database in spring profile. The key line is this: INIT=create domain if not exists jsonb as other
spring:
profiles: h2
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:testdb;INIT=create domain if not exists jsonb as other;MODE=PostgreSQL;DB_CLOSE_DELAY=-1
username: sa
password: sa
spring.jpa.hibernate.ddl-auto: create
Write the test:
// Postgres test
@SpringBootTest
class ExampleJsonbPostgres(@Autowired private val myEntityRepository: MyEntityRepository) {
@Test
fun `verify we can write and read jsonb`() {
val r = myEntityRepository.save(MyEntity("""{"hello": "world"}"""))
assertThat(myEntityRepository.findById(r.id).get().config).isEqualTo("""{"hello": "world"}""")
}
}
// H2 test
@ActiveProfiles("h2")
@SpringBootTest
class ExampleJsonbH2(@Autowired private val myEntityRepository: MyEntityRepository) {
@Test
fun `verify we can write and read jsonb`() {
val r = myEntityRepository.save(MyEntity("""{"hello": "world"}"""))
assertThat(myEntityRepository.findById(r.id).get().config).isEqualTo("""{"hello": "world"}""")
}
}
Alternatively you can try to define custom type per database in hibernate XML as described here: https://stackoverflow.com/a/59753980/10714479