Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty string field as null field

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?

like image 397
sammubr Avatar asked Nov 10 '17 11:11

sammubr


People also ask

Is an empty string equal to null?

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.

Can a string field be null?

In Delphi, string is a value type and therefore can't be null.

IS NULL same as empty string in SQL?

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.

Does SQL Server treat empty string as null?

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.


1 Answers

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;
    }
}
like image 96
C. Weber Avatar answered Oct 09 '22 13:10

C. Weber