0

我得到了错误。

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

4

2 回答 2

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
}
于 2013-04-17T16:15:32.030 回答
0

HibernateDaoSupport很长一段时间都有最终的getSessionFactorysetSessionFactory方法无法覆盖。

最初应该通过它来减轻 xml 配置,但也可以<property name="sessionFactory" ref="sessionFactory" />混合使用@Autowired注释。

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

于 2017-05-18T15:13:18.650 回答