23

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!


UPDATE

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:

  1. no getAsText, so my form was getting populated with "null" strings!
  2. my equality check is C++, not Java. When I tried the recommended setter, I just reloaded the post, which already contained the "null" strings. Once I cleaned all that up, everything started working.

Thanks for the help, and sorry for my "operator error"!

Brett

1

4 Answers 4

63

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));
}

instructions here

Sign up to request clarification or add additional context in comments.

4 Comments

See my comments to Bozho regarding registerCustomEditor not working in Spring 2.5.5
Well, I can't swear on 2.5.5, but I am quite sure on 2.5.6 and 3 that it sets the string to the null reference, it doesn't set a string with a value of "null." Perhaps if you added the offending code to your question we could help more?
See my edit to the original post. My bad, thanks for your patience.
Just a warning: @InitBinder can only configure binding of @ModelAttribute annotated parameters. It is useless for @RequestBody annotated parameters.
15

I know this is old, but I wasted about 2 or 3 hours until I found a very easy way to apply a StringTrimmerEditor with a binder for all my controllers.

Once again: I must remember to RTFM.

In spring 3.2 you can create a @ControllerAdvice-annottated controller class and use the @InitBinder-annotated method just like the example @Affe gave.

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-initbinder-advice

Here is an example:

@ControllerAdvice
@Controller
public class AppBindingInitializer {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

}

Hope it helps someone.

3 Comments

Why do you need @Controller and @ControllerAdvice annotations both on the same bean?
I'm sorry. Don't remember now and couldn't find easily a reason in google. :)
Yes, this works, And you do not need ControllerAdvice and Controller both.
2

Perhaps you can use a custom Binder

4 Comments

I tried that, but it returns a String. Trying setValue(null) left me with Strings == "null" (the four letter word "null", not the value null). Not quite what I was looking for!
can't you return null String?
Custom binder is right. Where you see this Strings == "null"; what are you doing? Are you building a SQL string, if so DONT. Use a Preprable.
Does this only work in older versions of Spring? I'm using 2.5.5 and it isn't working, even using the StringTrimmerEditor also suggested. The object I'm binding to is getting a String with the value of "null". I can pass the object back to a new webpage and I will have the text "null", so this isn't related to SQL at all. So I'm stuck thinking this only works for older versions of Spring. what else could it be?
0

Set the default value for your optional fields to NULL - actually is it not NULL by default?

Parse your input string and then explicitly specify only populated columns with

 usingColumns

oh, and I'd advise to always sanitise your inputs...

3 Comments

Mind telling me how to set the default value to NULL? I'm getting empty strings back, so I'm guessing NULL isn't the default.
I think it's the default, but you can also add an explicit DEFAULT NULL clause to each field. dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html NB - Note my strikethru - I read this initially outside the context of the SimpleJdbcInsert class
Ok, I have default NULL for the database. I thought you were refering to a way to set null as the default java String result for empty input on the form! The problem with usingColumns (I think) is that it takes (String ...) as the arguments - I need to hardcode them, not create a list of string arguments dynamically at runtime by checking the values. I could also have the getters return null for empty strings, which seems comparable, but again means checking every value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.