Home > Enterprise >  Agnostic default value for Boolean Types
Agnostic default value for Boolean Types

Time:02-04

Our application works correctly with Hibernate 5 and PostgreSQL for boolean types which need to have a default value with the columnDefinition = "bool default false" property of @Column annotation. Now we have to make the application work with Oracle and PostgreSql and we have to avoid using this columnDefinition as is not a valid value with Oracle. ¿How could we set the default value to these boolean fields? I can't change the actual boolean type in db and use things like TrueFalseType.

The only way I've found to have a similar behavior is creating a custom converter to avoid the null values

@Converter
public class Converter implements AttributeConverter<Boolean, Boolean> {

  @Override
  public Boolean convertToDatabaseColumn(Boolean aBoolean) {
    return Objects.nonNull(aBoolean) && aBoolean.booleanValue();
  }

  @Override
  public Boolean convertToEntityAttribute(Boolean aBoolean) {
    return Objects.nonNull(aBoolean) && aBoolean.booleanValue();
  }
}

and then annotate the entity property with @Convert(converter = Converter.class)

I'm not sure about this solution and if there could be a better solution

Thanks in advance!

CodePudding user response:

You do understand that a column default only take effect if you don't list the column in an insert statement? As soon as you map a column, Hibernate will always list the column in the insert statement, so the column defaults are useless. Just assign a non-null default value to the entity field.

  • Related