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?
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
In Delphi, string is a value type and therefore can't be null.
The concept of NULL and empty string often creates confusion since many people think NULL is the same as a MySQL empty string. However, this is not the case. An empty string is a string instance of zero length. However, a NULL has no value at all.
NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With