我正在尝试从数据库中查询单个对象,每当我执行应用程序时它会抛出一个空指针异常,但是当我查询整个表并将其放在列表中时,我得到所有结果所以那里我可以访问数据库的配置没问题。这是抛出错误的代码的一部分:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.erp.entity.User;
@Repository
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public User getUser(String username) {
Session currentSession = sessionFactory.getCurrentSession();
String hql = "FROM User WHERE username = '" + username + "'";
Query<User> query = currentSession.createQuery(hql, User.class);
User user = (User) query.getSingleResult();
return user;
}
@Override
@Transactional
public List<User> getUsers() {
Session currentSession = sessionFactory.getCurrentSession();
Query<User> query = currentSession.createQuery("FROM User", User.class);
List<User> users = query.getResultList();
return users;
}
}
这是抛出的错误:
Servlet.service() for servlet [dispatcher] in context with path [/ERPapplication] threw exception[Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.erp.dao.UsersDAOImpl.getUser(UsersDAOImpl.java:23) at com.erp.controller.LoginController.greeting(LoginController.java:39)
这是控制器类:
@Controller
@RequestMapping("/erp")
public class LoginController {
@Autowired
private UsersDAO usersDAO;
@RequestMapping("/list")
public String listUsers(Model model) {
List<User> users = usersDAO.getUsers();
model.addAttribute("users", users);
return "list-users";
}
@RequestMapping("/login")
public String login(Model model) {
return "login";
}
@RequestMapping("/test")
public String greeting(Model model) {
UsersDAO usersDAO = new UsersDAOImpl();
if(usersDAO.getUser("username").getUsername().equals("username")) {
return "greeting";
} else {
return "list-users";
}
}
}
答案 0 :(得分:1)
您在UsersDAO usersDAO = new UsersDAOImpl();
课程中使用Controller
。这是一个新实例,而不是使用Spring组件扫描创建的单例。使用Autowire
d UsersDao usersDao
来调用方法。我想你没注意到!