Unknown data type "JSONB" when running tests in play slick with H2 Database Unknown data type "JSONB" when running tests in play slick with H2 Database postgresql postgresql

Unknown data type "JSONB" when running tests in play slick with H2 Database


I recently had this problem with JSONB and H2 too. I solved it by creating an alias of JSONB to JSON and have it run only during the tests profile on H2.

CREATE TYPE "JSONB" AS json; 

It's not JSONB but the difference of JSONB to JSON (at least in postgres) is essentially the perfomance of reading, which for the test purposes doesn't really matter (so much).

Maybe this example helps too:

This is an example using flyway. Create an sql entry to create an alias type to jsonb on /resources/db/tests that runs only on the test profile.

We were using spring so here's the entrance on the application.yml:

spring:  profiles: mytest  datasource:    continueOnError: false    url: jdbc:h2:mem:myapp-db;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUEflyway:   enabled: true   locations: classpath:db/migration, classpath:db/tests  [......]

And heres a list of the ${project.dir}/resources/db/

enter image description here

Here's the magic:

In the content of the file I create a type called JSONB that is basically an alias to the JSON type. note: For what I've understood, Uppercase is necessary (specially when you're referring to it on the creation of the table) cause H2 seems to automatically change the types names to UPPERCASE:

CREATE TYPE "JSONB" AS json; 

Here is an example of a creation of a table with this type:

CREATE TABLE "XXX" (    id BIGSERIAL PRIMARY KEY,    my_json_column_name JSONB NOT NULL);

On the side of hibernate I use the type JsonBinaryType from hibernate-types52 See more on this link.

@Data@TypeDef(name = "jsonb", typeClass = com.vladmihalcea.hibernate.type.json.JsonBinaryType.class)@Entity(name = "XXX")@Table(name = "XXX")public class XXX {  @Type(type = "jsonb")  @Column(name = "my_json_column_name", nullable = false)  private String myJsonColumnName;  //OR  @Type(type = "jsonb")  @Column(name = "my_json_column_name", nullable = false)  private List<MYCustomTypeThatMatchesJsonObject> myJsonColumnName;}

I hope it helps someone. It worked for me.


UPDATED AT 2020-07-13

I stopped using H2 on my projects and started to use testcontainers. Very easy to setup and you can test in your real db environment.


H2 does not support JSONB column type.

All supported column types Supported datatypes of H2

Try to use postgres also in tests or write standard SQL statments which both databases understand.


You can not use PostgreSQL for unit test as you are connecting to something, unit test should only relay on in-memory test as it will be trigged by your build and it's very unlikely to have build server accessing any physical DB, you may need another way to mock your data and avoid DB accessing from it, or change your data type to string[] and encapsulate it to produce JSON