我得到了错误。
java.lang.NullPointerException
at org.springframework.orm.hibernate3.support.HibernateDaoSupport.getSession(HibernateDaoSupport.java:143)
at com.walladverts.model.dao.UserDao.findByUsername(UserDao.java:25)
在 findByUsername 中访问 getSession() 时
package com.walladverts.model.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.walladverts.exceptions.DataNotFoundException;
import com.walladverts.model.entities.User;
import com.walladverts.util.CustomHibernateDaoSupport;@
Repository("userDao")
public class UserDao extends CustomHibernateDaoSupport {
public void save(User user) {
getHibernateTemplate().save(user);
}
public void delete(User user) {
getHibernateTemplate().delete(user);
}
public User findByUsername(String username) throws DataNotFoundException {
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
System.out.println(username);
crit.add(Restrictions.eq("username", username));
crit.setMaxResults(1);
List < User > users = crit.list();
System.out.println(users);
if (users.size() < 1) {
throw new DataNotFoundException();
}
return users.get(0);
}
}
父类:
package com.walladverts.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport {@
Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
}
有人知道为什么会这样吗?它冻结了我的发展。
编辑:
当 Spring Secure 尝试登录用户时会发生这种情况。从 Controller 调用此方法时,我的 SessionFactory 也可以正常工作。