Hibernate,Spring,Dao getSession()NullPointerException

时间:2013-04-17 15:53:52

标签: java spring hibernate

我收到了错误。

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也正常工作。

2 个答案:

答案 0 :(得分:1)

public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport {
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
}

public User findByUsername(String username) throws DataNotFoundException {
     Session session = getSession();
     // do sth
}

答案 1 :(得分:0)

var editorNode = domWindow.document.getElementById("content-frame"); // GetCurrentEditor() equivalent: nsIEditor = editorNode.getEditor(editorNode.contentWindow) 很长一段时间都有最终的getSessionFactorysetSessionFactory方法无法覆盖。

最初应该通过HibernateDaoSupport缓解xml配置,但混合<property name="sessionFactory" ref="sessionFactory" />注释为also possible

您需要在需要时调用getSession()方法。