How can solve JSON column in H2

前端 未结 10 1842
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 13:39

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

相关标签:
10条回答
  • 2020-12-24 13:57

    A workaround is actually to create a custom column data type in H2 for the jsonb type, and put the query in the datasource url like this:

    spring.datasource.url=jdbc:h2:mem:testdb;INIT=create domain if not exists jsonb as text;MODE=PostgreSQL"
    

    Now for tests and integration tests in particular, it would be preferable to use the same DB than your application, via TestContainers

    0 讨论(0)
  • 2020-12-24 14:02

    In my case we were dealing with PostgreSQL jsonb type in production and H2 for our tests.

    I could not test @n00dle 's solution because apparently spring does not support executing a SQL script before Hibernate's ddl-auto=update for our tests so I used another way to solve this.

    Here is a gist for it.

    The overall idea is to create two package-info files. One for production and the other for tests and register different types (JsonBinaryType.class for production and TextType.class for tests) to handle them differently for PostgreSQL and H2

    0 讨论(0)
  • 2020-12-24 14:02

    This is how I solved it in Spring context:

    1. Create /src/test/resources/init.sql
    CREATE TYPE "JSONB" AS json;
    
    1. Configure H2 datasource as follows /src/test/resources/application-test.yml
    spring:
      datasource:
        driver-class-name: org.h2.Driver
        url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:init.sql'
        username: sa
        password: sa
    

    Source article

    0 讨论(0)
  • 2020-12-24 14:12

    JSON support was added to H2 after the question was asked, with version 1.4.200 (2019-10-14).

    However, you rarely need a JSON data type in a database. JSON essentially is just a potentially very long string, so you can use CLOB which is available on most databases.

    You do need the JSON data type if you need an SQL function that operates on them, and then only if the database insists that its JSON functions operate on a JSON type instead of on a CLOB. Such functions tend to be database-dependent though.

    0 讨论(0)
提交回复
热议问题