调用实体管理器时为NullPointer

时间:2018-08-26 19:30:38

标签: java spring hibernate

我尝试使用Java,Hibernate和Spring编写一些程序。调用SQL查询时,我看到NullPointerException。我可能尝试了Internet上所有的代码示例,但是我不知道该怎么做。我该如何解决?这是我的示例代码。我有完整的程序代码:https://github.com/lukasz-chojn/films_database/tree/master/src/main/java/Films

    @Controller
    public class DataFromUserController {
        private FilmDaoImpl filmDaoImpl = new FilmDaoImpl();
        private DirectorDaoImpl directorDaoImpl = new DirectorDaoImpl();
        private Locale locale = Locale.getDefault();
        private Scanner sc = new Scanner(System.in).useLocale(locale);

        public FilmDs collectData() {
            //....

            filmDaoImpl.insert(film);
            directorDaoImpl.insert(director);

            return film;
        }

        private String collectTitle() {
            System.out.print("Podaj tytuł filmu: ");
            String tytul = sc.nextLine();
            List<String> existingEntry = filmDaoImpl.existingTitle();
            if (existingEntry.contains(tytul)) {
                System.out.println("Tytuł jest już w bazie. Podaj inny");
                return collectTitle();
            }
                if (tytul.isEmpty()) {
                    System.out.println("Tytuł nie może być pusty. Podaj go");
                    return collectTitle();
                }
            return tytul;
        }//......
    }

    @Service
    @Transactional
    public class FilmDaoImpl implements FilmDAO {

        @PersistenceContext
        private EntityManager entityManager;

        //......
        @Override
        @SuppressWarnings("unchecked")
        public List<String> existingTitle() {
            List<String> titleInTheDatabase;
    // here is NPE
    return titleInTheDatabase = entityManager.createQuery("SELECT film.tytul FROM FilmDs film").getResultList();
        }

        //....
    }

1 个答案:

答案 0 :(得分:1)

您要自己创建实例,而不是让spring为您注入实例,这就是为什么您丢失所有依赖项(例如,entitymanager等)的原因。更改您的DataFromUserController

@Controller
public class DataFromUserController {

@Autowired
private FilmDAO filmDao;

@Autowired
private DirectorDAO directorDao;

.....
}