默认情况下,Spring将数据库中的空字符串字段保留为空字符串。有没有办法使用Spring Boot将所有空字符串字段从任何实体持久化为空字段?
答案 0 :(得分:3)
也许您可以尝试使用转换器:
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;
}
}