How to configure Hibernate (via Spring Boot) to use `NumericBooleanType` for all boolean columns

Viewed 1361

How can I configure Hibernate to use its built-in type NumericBooleanType for every boolean column without using any annotation (@Type) on each column?

Edit: A little more background - the goal is to support Oracle as well as Postgres with one codebase and since Oracle has no boolean type I want to make Postgres store boolean values like Oracle with 0/1

2 Answers

You don't have to do anything if your database column has a numeric datatype and the entity has a boolean attribute.

If this does not work use the @Type annotation:

@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean enabled;

Alternatively you could write a JPA Converter with auto apply:

@Converter(autoApply = true)
public class FileConverter implements AttributeConverter<Boolean, Short> {

  @Override
  public Short convertToDatabaseColumn(Boolean value) {
      return value ? 1 : 0;
  }

  @Override
  public Boolean convertToEntityAttribute(Short dbData) {
      return dbData == 1;
  }
} 

So with the help of this answer I was able to achieve what I want but it has the drawback that now I cannot explicitly configure Hibernate to fall back to its previous default mapping in case I would want to do that for some boolean fields. Hoping for more input from all of you :)

public class NumericBooleanTypeAsDefaultBooleanTypeRegistration implements SessionFactoryBuilderFactory {

    private static final Logger logger = LoggerFactory.getLogger(NumericBooleanTypeAsDefaultBooleanTypeRegistration.class);

    @Override
    public SessionFactoryBuilder getSessionFactoryBuilder(final MetadataImplementor metadata,
            final SessionFactoryBuilderImplementor defaultBuilder) {
        logger.info("Overriding BooleanType with NumericBooleanType as default Boolean type");
        metadata.getTypeConfiguration().getBasicTypeRegistry().register(new NumericBooleanType(),
                new String[] {"boolean"});
        return defaultBuilder;
    }
}

and as explained in the referenced answer I have to tell Hibernate about this class via the ServiceLoader mechanism:

  • Create the file src/main/resources/META-INF/org.hibernate.boot.spi.SessionFactoryBuilderFactory with the content mypackage.NumericBooleanTypeAsDefaultBooleanTypeRegistration
Related