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"?
views:
259answers:
3First, 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.
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.
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).