Java: dbUnit add support of jsonb type in the H2 mem db with Postgres mode

Task: add support of json data type in the H2 mem db with Postgres mode

Implementation steps:

  1. Add into maven/gradle dependency:
    com.vladmihalcea:hibernate-types-52:2.19.2
  2. Declare jsonb type in the entity class:
    @TypeDef(name = “jsonb”, typeClass = JsonBinaryType.class)
  3. Use this type in the property declaration:
    @Type(type = “jsonb”)
  4. Use this type in the column definition:
    @Column(name = “content”, columnDefinition = “jsonb”, nullable = false)
    private Map<String, Object> content;
  5. Modify db connection link to (add marked init block):
    spring.datasource.url=jdbc:h2:mem:testdb;INIT=create domain if not exists jsonb as text;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH;DB_CLOSE_DELAY=-1;NON_KEYWORDS=PUBLIC,PUBLIC1,DEFAULT,DEFAULT1,VALUE,VALUE1

Example of entity with jsonb type (part):

package com.scalan.testapp.persistences;

import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.MappedSuperclass;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

@Getter
@Setter
@MappedSuperclass
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class MyDBEntity implements Serializable {

   ...

   @Type(type = "jsonb")
   @Column(name = "content", columnDefinition = "jsonb", nullable = false)
   private Map<String, Object> content;

   ...
}

Done.

Leave a Reply

Your email address will not be published.

6  +  2  =