I'm using Spring MVC and SimpleJdbcInsert to insert objects into a MySQL database. I'd like to set the blank input to NULL
in the database rather than ''
. I have quite a few fields, and I'm hoping for a way to do this without manually checking every value.
Thanks!
So I'm an idiot. Several errors combined on my part led me to believe the correct answers below were not correct. I'd written a PropertyEditorSupport like this:
class StringEditor extends PropertyEditorSupport {
public void setAsText(String text) {
String value = text.trim();
if ("" == value) {
setValue(null);
} else {
setValue(value);
}
}
}
There are two problems:
Thanks for the help, and sorry for my "operator error"!
Brett
The class you're looking for is:
org.springframework.beans.propertyeditors.StringTrimmerEditor
If you construct it with a true
it will convert empty/whitespace strings to null. How to get it registered onto the binder depends on if you want it to be the default or only apply to certain views.
e.g., on a single controller you can just add
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}