使用spring-mvc和hibernate

时间:2015-11-11 10:47:13

标签: java spring hibernate spring-mvc

这是我的代码: 我的模特课:

@Entity
@Table(name="admin")
public class Admin extends Profile{
    public Admin(){}

    public Admin(String mail, String name, String lastName, String password, Date birthDate, int gsm){
        super(mail, name, lastName, password, birthDate, gsm);
    }
}

DAO课程:

@Repository
public class AdminDAO {

    private static final Logger logger = LoggerFactory.getLogger(AdminDAO.class);

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }
    @SuppressWarnings("unchecked")
    public List<Admin> listAdmins() {
        Session session = this.sessionFactory.getCurrentSession();
        List<Admin> adminsList = session.createQuery("from Admin").list();
        for(Admin a : adminsList){
            logger.info("Admin List::"+a);
        }
        return adminsList;
    }
}

我的服务类:

@Service

    public class AdminService {

        @Autowired
        private AdminDAO adminDAO;

        public void setAdminDAO(AdminDAO adminDAO) {
            this.adminDAO = adminDAO;
        }
        @Transactional
        public List<Admin> listAdmins() {
            return this.adminDAO.listAdmins();
        }
    }

当我运行我的代码时,我收到此错误消息:

  

显示java.lang.NullPointerException   在com.journaldev.spring.dao.AdminDAO.listAdmins(AdminDAO.java:38)

我在我的数据库中手动添加了一个管理员,但它仍然显示空指针异常 我做错了什么? 注意:我有另一个工作正常的类,它获取所有实体,当数据库为空时,它不会生成空指针异常

1 个答案:

答案 0 :(得分:1)

您错过了@Autowired的setter方法的@InjectadminDAO注释。它必须是

@Autowired
public void setAdminDAO(AdminDAO adminDAO) {
    this.adminDAO = adminDAO;
}

您必须使用@Autowired@Inject注释Bean的所有依赖项。