8

By default, Spring persists empty string fields in the database as empty string. Is there any way to persist all empty string fields, from any entity, as null fields, using Spring Boot?

sammubr
  • 535
  • 1
  • 4
  • 23

1 Answers1

19

Maybe you could try to use a converter:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.apache.commons.lang.StringUtils;

@Converter(autoApply = true)
public class EmptyStringToNullConverter implements AttributeConverter<String, String> {

    @Override
    public String convertToDatabaseColumn(String string) {
        // Use defaultIfEmpty to preserve Strings consisting only of whitespaces
        return StringUtils.defaultIfBlank(string, null);
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        //If you want to keep it null otherwise transform to empty String
        return dbData;
    }
}
C. Weber
  • 907
  • 5
  • 18