Saturday, August 26, 2017

org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type.

Some of you might have faced the above exception and some of you might not as the exception does not happen on normal scenario.  Therefore it is a bit tricky to resolve the issue for the novice developers working on hibernate. As the error suggest assignment of Null value to primitive data type.  That means you are assigning null value to any variable that has been declared as primitive data type.

Cause:

The specific reason for the above exception depends upon the application you are developing, but the main reason for the exception you are assigning null value to a variable declared as primitive data type.  So, if you have a variable of boolean, char, byte, short, int, long, float, double and assigning null value in any way. Check the stack trace of the exception and find the exact line in the code.

Solution:

1.       In the hibernate application check the setter method of the variable for which you are getting the exception. Make sure to check the value you are assigning is not null. In case the value is null then assign default value.
2.       In case your application getting values from table of a database, check if the field in the table contains null value. Update the table with default value for existing records. Add a default value for the field in the table so that in case of new record, it will have a default value rather than null, this helping the setter function to assign default value to the variable declared in the class

3.       Thirdly instead of using primitive data type, you can use wrapper class to declare the variable for which value is being assigned, for example you can use Integer for int or Float for float.

No comments:

Post a Comment