5
votes

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?

1
using Spring Boot? Whats the meaning? - Bikramjit Rajbongshi
Sorry, I mean using Spring Data and/or Hibernate Annotations. - sammubr
Why are the fields set to en empty string? Set them null and they will be saved as null in the DB. - Tom

1 Answers

10
votes

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;
    }
}