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"?
Hi, You could use a string instead of boolean and set it to "False", "True" or "" where the empty string represents your null value. Alternatively you need for every Boolean an extra Boolean like <attribute>IsSpecified which you set to false if the attribute value false means null.
BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL.
The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table. Auto-boxing is your friend.
to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context. each time a method needs an Object as argument, and you need to pass a boolean value.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With