Sunday 9 November 2014

Java exception: null value was assigned to a property of primitive type setter



When adding a new property to an existing entity, Java might complain that 'null value was assigned to a property of primitive type setter' at run time.
The reason is the existing entities have null value in the database for the newly added column.


The SQL query to add a property might look like below:

alter table registration add column cost double precision;

One way to overcome this is to use below get method instead of the standard one.




 public void setCost(final Double cost)  
 {  
  _cost = cost;  
 }  
 public static Double getCost(final Double cost)  
 {  
  if (cost == null)  
  {  
   return new Double(0.0);  
  }  
  else  
  {  
   return cost;  
  }  
 }  




Another way would be setting default value for the newly field in the database, which might not always easy for a large live production database. The SQL query might look like below:


alter table registration add column cost double precision default 0