0

Trying to retrive values from database with @Query("From UshtaretEntity"); but i am getting an erorr the famous one NullPointerExceptions seems like EkipaRepository is throwing exception

@Repository
    public interface EkipaRepository extends CrudRepository<EkipaEntity,Long>  {
    
        @Query("FROM UshtaretEntity ")
         List<UshtaretEntity> getAll();
    
    }

public class testMain {

@Autowired
private EkipaRepository ekipaRepository;

public testMain(){

}

public List<UshtaretEntity> getAllEkipet(){

    return ekipaRepository.getAll(); // line 28
}

public static void main(String[] args) {

    testMain t = new testMain();

    List<UshtaretEntity> lista = t.getAllEkipet(); // line 35
     System.out.println(lista);
    System.out.println(lista.size());

}

} *Error

Exception in thread "main" java.lang.NullPointerException
    at com.example.demo.testMain.getAllEkipet(testMain.java:28)
    at com.example.demo.testMain.main(testMain.java:35)
  • This can also mean that the autowired repository is null and hence the error since the stack trace points to line 28. Please check if ekipaRepository is null ? – Avinash Sagar Dec 06 '20 at 22:57
  • Hi Avinash thank you for commenting, i know the ekipaRepository is null but what do i need to do to get rid of the nullPointerException? –  Dec 06 '20 at 23:00
  • @AvinashSagar is right. It would seem that Spring is not autowiring your dependancy for you. I would use constructor injection instead of field injection so that Spring will throw an error that can be investigated instead of just silently not injecting anything (constructor injection disrupts object creatino if the dependancy cant be loaded). – theChoosyBeggar Dec 06 '20 at 23:02
  • I think @Query("FROM UshtaretEntity ") List getAll(); is returing null can that be the problem that is throwing NullPointerException when i am calling the method –  Dec 06 '20 at 23:09
  • @thymeleaf it is not returning null, because returning null does not throw the NullPointerException. The `ekipaRepository` is null, because the main method called as written in the example does not utilize the spring engine at all, so the @Autowired field has its value as declared in the class - that is null. – JockX Dec 06 '20 at 23:28
  • @thymeleaf if that were true then the exception wouldn't have been thrown on line 28. Returning null doesn't throw a nullpointerexception, only attempting to do something with null does. And btw if you change your field's signature to ```private EkipaRepository ekipaRepository;``` youll be able to use it in your main method without having to create instance of the class (not good practice). – theChoosyBeggar Dec 06 '20 at 23:29
  • (1) Always use constructor injection whenever possible and make your fields `final`; this will prevent this error. (2) Use `CommandLineRunner`. – chrylis -cautiouslyoptimistic- Dec 07 '20 at 00:19

0 Answers0