Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert the null value in a Boolean attribute when using Hibernate?

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"?

like image 447
Pedro Rolo Avatar asked Jun 01 '10 15:06

Pedro Rolo


People also ask

How do you set a boolean to null values?

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.

Can you have null in boolean?

BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL.

How hibernate handle null values?

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.

How do you handle a boolean null?

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.


2 Answers

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.

like image 118
Marc Avatar answered Sep 30 '22 12:09

Marc


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).

like image 25
Pascal Thivent Avatar answered Sep 30 '22 14:09

Pascal Thivent