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
My problem was with JSONB since H2 does not support it as was already mentioned.
One more problem is that when you insert a json, H2 transforms it into a json object string which makes jackson serialization fail. ex: "{\"key\": 3}" instead of {"key": 3} . One solution is to use FORMAT JSON when inserting the json, but then you need to have duplicate insert files if you are using flyway, for example.
Inspired by the @madz answer I came across with this solution:
Create a custom JsonbType (on production - e.g. main/java/com/app/types/JsonbType.java)
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
public class JsonbType extends JsonBinaryType {
private static final long serialVersionUID = 1L;
}
Create a custom JsonbType (on tests - e.g. test/java/com/app/types/JsonbType.java)
import com.vladmihalcea.hibernate.type.json.JsonStringType;
public class JsonbType extends JsonStringType {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "jsonb";
}
}
Create an alias type from JSONB to JSON only on tests (h2):
-- only on H2 database
CREATE TYPE "JSONB" AS TEXT;
note: I'm using flyway which make it easy to do but you can follow @jchrbrt suggestion
Finally you declare the type on your entity model, as follows:
import com.app.types.JsonbType;
@TypeDef(name = "jsonb", typeClass = JsonbType.class)
@Entity(name = "Translation")
@Table(name = "Translation")
@Data
public class Translation {
@Type(type = "jsonb")
@Column(name="translations")
private MySerializableCustomType translations;
}
}
That's it. I hope it helps someone.