views:

259

answers:

3

I have a class with a Boolean attribute. When I instantiate and persist this class, the Boolean attribute is stored with the "false" value instead of the expectable "null". How can I set a Boolean attribute to "Null"?

+2  A: 

First, make sure that you define a Boolean object and not a boolean type.

Then, if you are using Hibernate with JPA attributes, then you can add @Column(nullable=true) to explicitly tell Hibernate the the column should have NULL as default.

Marc
@Marc nullable attribute is, by default, true
Arthur Ronald F D Garcia
This does no work...
Pedro Morte Rolo
What is the schema of your table? Does it allow for NULL values in that column?Furthermore, you can try debugging the code where you create a new instance. Maybe the value is initialized to false in your code.
Marc
The value is explicitly initialized to "null", the "schema" represents this attribute as a tinyint with null as default value
Pedro Morte Rolo
Have you tried putting your Boolean value as null as default?`Boolean value = null;`
Shervin
+2  A: 

First you make sure that the object you are trying to persist is Boolean not primitive boolean. Secondly, you can define the column corresponding as char(1) which can hold 'Y', 'N' or null value. and lastly,and the most important add the following line to you hibernate.cfg.xml :-

<property name="query.substitutions">'Y'=true,'N'=false</property>

if u are using hibernate.properties file then use following:-

hibernate.query.substitutions true 'Y', false 'N'

this would help you out to store null values to boolean type column. and don't forget to map the property as type="boolean" in the mapping file.

Mrityunjay
+2  A: 

This is a weird problem. A Boolean attribute with a null value is definitely supposed to be stored as NULL and the tinyint column type allows that. I cannot investigate the problem myself but here is what I would do:

First, I would activate the logging of Hibernate's DML statements and of JBDC parameters to confirm that Hibernate is actually passing NULL (and it should). The relevant categories (chapter 3.5. Logging) are org.hibernate.SQL and org.hibernate.type.

If the first test doesn't reveal the problem, I would try to isolate it further with a simple test class using raw JDBC to insert a Boolean with a null value (and also read it). If this test is not positive, then I would start to suspect the JDBC driver.

What JDBC driver (and version) are you using by the way? If you are using the Microsoft driver, try with the latest version of jTDS (and inversely).

Pascal Thivent