Q: @Query in JPA throwing null pointer exception I am getting nullPointerException from my custom jpa method findShiftNameById() in my shift planner project(github link below). I have used @Query annotation inside ShiftDetailsRepo Interface to implement the method. Please check and let me know what could be causing this. I tried by removing nativeQuery parameter but that gives shift_details not mapped error.I tried by changing datatypes between int and long and also by changing sd.shiftName to sd.shift_name(as per the column name that is available in my actual database) but still same nullPointerException error is coming.
Github link-https://github.com/Anupam5713/shiftPlannerAPI
The method is being called in the ShiftPlanService Class inside the service package
Is there something wrong in my query?
@Query(value = "select sd.shiftName from shift_details sd where sd.shiftId=:shiftId",nativeQuery=true)
    public String findShiftNameById(@Param("shiftId") int shiftId);


A: The following is the cause of NPE.  The call to sdr is done before the dependencies are wired.
@Service
public class ShiftPlanService {

    @Autowired
    ShiftDetailsRepo sdr;
    String S1 = sdr.findShiftNameById(1);
    String S2 = sdr.findShiftNameById(2);

Move these initializations to a @PostConstruct method.
Example
@PostConstruct
public void initDetails() {
    S1 = sdr.findShiftNameById(1);
    S2 = sdr.findShiftNameById(2);
}

