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?
Asked
Active
Viewed 8,126 times
8
-
using Spring Boot? Whats the meaning? – Bikramjit Rajbongshi Nov 10 '17 at 11:17
-
Sorry, I mean using Spring Data and/or Hibernate Annotations. – sammubr Nov 10 '17 at 11:31
-
Why are the fields set to en empty string? Set them null and they will be saved as null in the DB. – Tom Nov 10 '17 at 13:10
1 Answers
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
-
Nice Solution. Really helpful. I was about to start searching overriding jackson. – nick kladis Oct 25 '21 at 08:32