1

I'm new to spring r2dbc. Previously I've user hibernate. In hibernate when you need to map postgresql enum to java enum you just add com.vladmihalcea:hibernate-types-52 and use @Enumerated (as shown bellow). Related to R2DBC and enum (PostgreSQL) SO question I have to create codec for every single enum. Is it possible to achive this with some kind of tag or other general solution not just creating multiple codecs.

CREATE TYPE user_type_enum AS ENUM ('ADMIN', 'USER');
public class PostgreSQLEnumType extends org.hibernate.type.EnumType {
  public void nullSafeSet(PreparedStatement st, Object value,
      int index, SharedSessionContractImplementor session)
      throws HibernateException, SQLException {
    st.setObject(
      index,
      value != null ? ((Enum) value).name() : null,
      Types.OTHER
    );
  }
}
public enum UserTypeEnum {
  ADMIN,
  USER
}
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

@Table;
@TypeDef(
    name = "pgsql_enum",
    typeClass = PostgreSQLEnumType.class
)
public class User {

  @Id
  private Long id;

  private String usename;

  @Enumerated(EnumType.STRING)
  @Type(type = "pgsql_enum")
  private UserEnumType userType;

  // Getters and setters provided
}
Petar Toshev
  • 67
  • 1
  • 1
  • 9

1 Answers1

1

You don't need to create your own codecs anymore. See https://github.com/pgjdbc/r2dbc-postgresql#postgres-enum-types

DDL:

CREATE TYPE my_enum AS ENUM ('FIRST', 'SECOND');

Java Enum class:

enum MyEnumType {
  FIRST, SECOND;
}

Your R2DBC ConnectionFactory bean:

PostgresqlConnectionConfiguration.builder()
.codecRegistrar(EnumCodec.builder()
.withEnum("my_enum",MyEnumType.class)
.build());

Note that you must use lower case letter for your "my_enum" in withEnum, otherwise won't work.

Also, you will need to provide a converter that extends EnumWriteSupport, and register it. See: https://docs.spring.io/spring-data/r2dbc/docs/current/reference/html/#mapping.explicit.enum.converters

For example:

@Configuration
public static class R2DBCConfiguration extends AbstractR2dbcConfiguration {
        @Override
        @Bean
        public ConnectionFactory connectionFactory() {
            ...
        }

        @Override
        protected List<Object> getCustomConverters() {
            return List.of(
                new MyEnumTypeConverter()
            );
        }
    }
Eric
  • 11
  • 3