Skip to content
Advertisement

How to handle an error when database returns null value for one of the columns in the table

I’m using Java and Spring Boot with JPQL to access the data.

I’m getting the below error because hourlyRate is null in the database:

Caused by: org.hibernate.QueryException: could not instantiate class [com.example.model.response.school.Employee] from tuple.

I still would like to be able to get the data from the database even when that column has null value in the database and send the response as null value instead of getting an error. How can I handle that?

Here is the POJO:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee{
   
   private String firstName;
   private String lastName;
   private float hourlyRate;
}

Here is the DAO:

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements java.io.Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "EMPLOYEE_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer employeeId;

    @Column(name = "FIRST_NAME")
    private String firstName;
    
    @Column(name = "LAST_NAME")
    private String lastName;
    
    @Column(name = "HOURLY_RATE")
    private float hourlyRate;

Here is the JPQL:

@Query("SELECT new com.example.model.response.school.Employee(e.firstName, e.lastName, e.hourlyRate FROM Employee e n" +
  " WHERE e.employeeId = :employeeId")
Employee getEmployeeDetails(@Param("employeeId") int employeeId);

Advertisement

Answer

If the value can be semantically null (undefined), then you should use Float (or probably BigDecimal) to save it, since those can represent null. If it can’t be correctly null, your column should be defined NOT NULL. Don’t try to do a magic mapping; instead, ensure that the definition of “correct” is the same in your code and in your schema.

Advertisement