Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set boolean to null

Tags:

I have a class Shop with the following variable

@Column(columnDefinition = "bit") private boolean atShop; 

Using this value, I am using HSQL to retrieve this information from the application

from Person person left join fetch person.shop 

when I try call this HSQL statement i get the following error

org.springframework.orm.hibernate3.HibernateSystemException: could not set a field value by reflection setter of com.test.dataobject.Shop.atShop; nested exception is org.hibernate.PropertyAccessException: could not set a field value by reflection setter of com.test.dataobject.Shop.atShop 

It is throwing this because it is trying to set the boolean to null in the HSQL. I can solve this problem by changing private boolean atShop; to private Boolean atShop; but i want to keep this as a boolean as i am saving it as a bit in my database

Is there a way to solve this without changing boolean to Boolean?

EDIT:

I know that boolean can only be true/false and Boolean can be set to null, but is there a way to get hibernate/spring to set this value to false(which i thought it should do automatically) instead of trying to set it to null and throwing this exception?

I have also tried adding annotation to automatically set the value to false but this does not work either

@Column(nullable = false, columnDefinition = "bit default 0") private boolean atShop; 
like image 728
Hip Hip Array Avatar asked Oct 22 '12 14:10

Hip Hip Array


People also ask

Can you set a Boolean to null?

Nullable boolean can be null, or having a value “true” or “false”. Before accessing the value, we should verify if the variable is null or not. This can be done with the classical check : if … else …

How do you make a Boolean nullable?

x = null. Use the Nullable<T>. GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.

Is null a valid Boolean?

A null Boolean means that the variable has no reference assigned, so it is neither true nor false, it is “nothing”.


1 Answers

- boolean is a primitive type, and can have a value of only true or false.

- Whereas Boolean is a Wrapper Object and can be given a null value.

- From Java 1.5 AutoBoxing is provided, so you can convert boolean to Boolean and back to boolean with Simple assignment operator (=), So you can do this in places where you want Boolean instead of boolean.

like image 165
Kumar Vivek Mitra Avatar answered Oct 19 '22 20:10

Kumar Vivek Mitra