简体   繁体   中英

Bind null value to a Boolean checkbox

It's needed to save a null value to a Boolean variable. When I tried to submit a form with no one inputs checked, I've got a "false" in myVariable instead of null. The property has Boolean type on the form. Here is a part of my jsp code:

<spring:bind path="form.myVariable">
<table cellpadding="0" cellspacing="0" border="0" >
    <td valign="middle">
        <input type="checkbox" name="<c:out value="${status.expression}"/>" value="true" <c:if test='${status.value == "true"}'>checked</c:if> />
    </td>
    <td valign="middle">
        <input type="checkbox" name="<c:out value="${status.expression}"/>" value="false" <c:if test='${status.value == "false"}'>checked</c:if> />
    </td>
    <input type="hidden" name="_<c:out value="${status.expression}"/>" value="">
</table>

The property are configured in hbm.xml like this:

<property name="myVariable" not-null="false" type="java.lang.Boolean" access="field" column="MY_VARIABLE"/>

I've also added CustomBooleanEditor to the binder in my controller:

binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("true", "false", true));

What's wrong with it?

The property has a Boolean type in your template . HTML checkboxes aren't tristate, they're either true or false.

Your hbm.xml configuration has not-null="false", hibernate does not expect to deal with null values. So your database should not give to hibernate a null value for this field, so perhaps hibernate handlea null value as false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM