Last updated: 2022-11-03
Bind empty String as null in Spring Boot
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. Best practices included.
Discover more
When a form is submitted with an input field without any data, the browser submits it as an empty string ""
. That's why Spring Boot writes this to the data object exactly this way - with a StringTrimmerEditor
configuration in place, we can bind the value as null
instead.
Configuration to convert empty Strings to null
The above ControllerAdvice
adds a new editor to our WebDataBinder
. StringTrimmerEditor
first removes all spaces at the beginning and end of the submitted form data (trim) - this is usually just an incorrect input from the user. With the parameter true
empty Strings will also be converted to null
.
This saves us from handling different cases separately and allows us to persist the data directly into the database, where we prefer to store a null
value when no information was provided.
Bootify is a tool to intialize Spring Boot applications with its own database schema, an optional Thymeleaf frontend with CRUD functionalities and many more features on top - online in the browser without registration. When a frontend is selected, the StringTrimmerEditor
is also provided exactly as described above.
Start Project
No registration required