gpt4 book ai didi

java - Hibernate、Spring、Dao getSession() NullPointerException

转载 作者:行者123 更新时间:2023-12-01 14:39:59 25 4
gpt4 key购买 nike

我收到错误。

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

最佳答案

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
}

关于java - Hibernate、Spring、Dao getSession() NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com