调用Service方法时,找不到当前线程的Session

时间:2014-11-09 17:58:43

标签: spring hibernate session

我尝试调用返回管理员列表的方法,但是当我调用此方法时,我得到的错误没有找到会话。

袋鼠-context.xml中

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <!-- Root Context: defines shared resources visible to all other web components -->

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
        <property name="username" value="HR" />
        <property name="password" value="asdfghj" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="pl.piotr.ibank.model" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.Oracle10gDialect
                </prop>
                <prop key="hibernate.show_sql">
                    true
                </prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="myAuthenticationSuccessHandler" class="pl.piotr.ibank.security.MyAuthenticationSuccessHandler" />

</beans>

的servlet上下文:

    <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->
    <context:component-scan base-package="pl.piotr.ibank" />

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

UserServiceImpl:

    package pl.piotr.ibank.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.piotr.ibank.daointerface.UserDao;
import pl.piotr.ibank.model.User;
import pl.piotr.ibank.serviceinterface.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public void createUser(User user) {
        userDao.createUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public void deleteUser(int id) {
        userDao.deleteUser(id);
    }

    @Override
    public User getUser(int id) {
        return userDao.getUser(id);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public List getAdminList() {
        return userDao.getAdminList();
    }

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

}

UserService接口:

    package pl.piotr.ibank.serviceinterface;

import java.util.List;

import pl.piotr.ibank.model.User;

public interface UserService {

    void createUser(User user);

    void updateUser(User user);

    void deleteUser(int id);

    User getUser(int id);

    @SuppressWarnings("rawtypes")
    List getAdminList();

    User findByUsername(String username);
}

在UserDAOImpl

    package pl.piotr.ibank.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import pl.piotr.ibank.daointerface.UserDao;
import pl.piotr.ibank.model.User;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void createUser(User user) {
        getCurrentSession().save(user);

    }

    @Override
    public void updateUser(User user) {
        getCurrentSession().update(user);

    }

    @Override
    public void deleteUser(int id) {
        User user = getUser(id);
        if (user != null) {
            getCurrentSession().delete(user);
        }

    }

    @Override
    public User getUser(int id) {
        User user = (User) getCurrentSession().get(User.class, id);
        return user;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public List getAdminList() {
        return getCurrentSession()
                .createQuery(
                        "from User u, UserRole ur where u.id = ur.user.id and ur.user = 'ROLE_ADMIN'")
                .list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public User findByUsername(String username) {

        List<User> users = new ArrayList<User>();
        System.out.println(username);

        try {
            users = getCurrentSession()
                    .createQuery("from User where username=:username")
                    .setParameter("username", username).list();

            System.out.println("Liczba " + users.size());

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        if (users.size() > 0) {
            return users.get(0);
        } else {
            return null;
        }
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

}

UserDao界面:

    package pl.piotr.ibank.daointerface;

import java.util.List;

import pl.piotr.ibank.model.User;

public interface UserDao {

    void createUser(User user);

    void updateUser(User user);

    void deleteUser(int id);

    User getUser(int it);

    @SuppressWarnings("rawtypes")
    List getAdminList();

    User findByUsername(String username);
}

调用getAdminList的控制器:

    package pl.piotr.ibank.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pl.piotr.ibank.model.User;
import pl.piotr.ibank.serviceinterface.UserService;

@Controller
public class AdminController {

    @Autowired
    private UserService userService;

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/admin/adminlist", method = RequestMethod.GET)
    public ModelAndView goAdminList() {
        ModelAndView mav = new ModelAndView("admin/adminlist");
        List<User> admins = userService.getAdminList();
        mav.addObject("admins", admins);
        return mav;
    }
}

登录方法工作正常,loadbyusername,但是当我调用方法service.getAdminList()时我有这个错误:

  

SEVERE:Servlet [appServlet]的Servlet.service()在路径[/ ibank]的上下文中引发异常[请求处理失败;嵌套异常是org.hibernate.HibernateException:找不到具有根本原因的当前线程的Session   org.hibernate.HibernateException:找不到当前线程的会话

1 个答案:

答案 0 :(得分:0)

我发现在您的代码中,您自动连接了会话&#39;在您的DAO工具中,这意味着您需要手动处理会话,包括必要时打开会话和关闭会话。由于您使用的是Spring和hibernate,我建议使用像HiberateTemplate这样的模板,Spring会为您处理会话。每次要使用会话时,只需调用&#39; getCurrentSession()&#39;,就像你在代码中所做的一样。

尝试创建一个扩展HibernateDaoSupport的抽象DAO类,如

公共抽象类BasicDAO扩展了HibernateDaoSupport {    ...... }

对于您的DAO工具,扩展此类,您的代码可以正常工作。