spring-bootjpah2jpa-2.0

Cannot create a table in H2 with a custom enum


We have an entity, let's call it Test.

@Entity
@Table(name = "TEST", schema = "KAA")
public class Test implements Serializable {

    @Id
    @Column(name = "ID", columnDefinition = "uuid", unique = true)
    private UUID id;

    @Column(name = "name", columnDefinition = "name")
    private String name;

    @Column(name = "blah", columnDefinition = "enum??")
    private Blah blah = Blah.A;

//..etc

}

The type Blah is an enum that looks like this :

public enum Blah {

    A("A"),
    B("B");

    private final String name;

    private Blah(String s) {
        name = s;
    }

    public String toString() {
        return this.name;
    }
}

How is it possible to persist the enum type in the H2 database? The H2 database cannot intiailise the table with this enum type.

In my spring boot configuration I have this:

spring.datasource.url=jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS KAA
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

Apparantly you can override the INIT in the config.

INIT=CREATE DOMAIN IF NOT EXISTS enum as VARCHAR(255);

As I already have an INIT in my config, appending this INIT does not seem to work.

If I append like this

spring.datasource.url=jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS KAA;INIT=CREATE DOMAIN IF NOT EXISTS enum as VARCHAR(255)

It says that the INIT is doubled.

If I comma seperate it :

spring.datasource.url=jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS KAA,INIT=CREATE DOMAIN IF NOT EXISTS enum as VARCHAR(255)

It says there is a syntax error.

Does anyone know how to write the INIT properly, and more generally, how to go about enums in a H2 database?


Solution

  • Have you tried using the @Enumerated(EnumType.STRING) annotation on the blah field? No columnDefinition or other stuff should be necessary... If you really want H2 to use the enum type, you can create the column with the enum data type which would be columnDefintion="ENUM('A', 'B')"...