简体   繁体   中英

can't get data from database using spring-mvc and hibernate

this is my code: my model class:

@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);
    }
}

the DAO class:

@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;
    }
}

my Service class:

@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();
        }
    }

when i run my code i get this error message:

java.lang.NullPointerException at com.journaldev.spring.dao.AdminDAO.listAdmins(AdminDAO.java:38)

i added an admin manually in my database, but it still showing the null pointer exception what i am doing wrong ?? note: i have another class that works fine, it gets all entities and when the database is empty, it doesn't generate null pointer exception

You missed the @Autowired or the @Inject annotation for the setter method for adminDAO . It has to be

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

You have to annotate all dependencies of your Bean with @Autowired or @Inject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM