java方法返回null值

时间:2015-08-10 11:12:57

标签: java spring spring-mvc

使用Spring MVC进行项目。基本是:当学生报名时,他的数据将存储在数据库表中,密码将被发送到学生的邮箱地址。

所以我有:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String dosignup(@Valid @ModelAttribute("student") Student student, HttpServletRequest request,
  HttpServletResponse response, BindingResult result) {

    studentService.addNewStudent(student.getName(),
        student.getUsername(), student.getEmail(), student.getPassword());
    studentService.sendEmail(student);
}

StudentDao界面是:

public interface StudentDao {
    public void saveStudent(Student student);
    public void fetchinfo(Student student);
}
fetchinfo中的

StudentDaoImpl实施是:

public void fetchinfo(Student student) {
    String hql = "select password from student where email = :email";
    sessionFactory.getCurrentSession().createSQLQuery(hql)
        .setParameter("email", student.getEmail()).uniqueResult();
}

StudentService界面是:

public interface StudentService {
    Student addNewStudent(String name, String username, String email, String password);
    void sendEmail(Student student);
    Student fetchinfo(String email);
}

StudentServiceImpl是:

public User fetchinfo(String email) {
    Student student = new Student(email);
    studentDao.fetchinfo(student);
    return student;
}

public void sendEmail(Student student) {
    mailService.accountActivation(student);
}

现在,问题是:邮件会发送到学生的邮箱地址,但密码为null。有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

StudentDaoImpl中,您没有从db查询结果中设置password属性。将相关行重写为:

student.setPassword(sessionFactory.getCurrentSession().createSQLQuery(hql)
    .setParameter("email", student.getEmail()).uniqueResult());

<强>更新

当我们处于Hibernate时,按照惯例,Student实体应该为每个属性设置getter和setter。然后我会将StudentDaoImpl重写为:

public void fetchinfo(String email) {

    String hql = "select s from student s where s.email = :email";

    return (Student)sessionFactory.getCurrentSession().createSQLQuery(hql)
      .setParameter("email", email).uniqueResult();

}

..并使用student = studentDao.fetchinfo(email);调用它(当然命名方法应该更改)。