本文介绍了Spring 和 hibernate:未找到当前线程的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误

org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1024)
at com.fexco.shoptaxfreemobile.service.ProfileService.registerVisitor(ProfileService.java:57)
at com.fexco.shoptaxfreemobile.controller.ProfileController.registerVisitor(ProfileController.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.fexco.shoptaxfreemobile.jsonp.JsonpCallbackFilter.doFilter(JsonpCallbackFilter.java:33)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

服务类

@Service
public class ProfileService {

    @Resource(name = "mySessionFactory")
    private SessionFactory sessionFactory;

    @Autowired
    private ProfileDao profileDao;

    private class CountrySorter implements Comparator<Country> {
        @Override
        public int compare(Country country1, Country country2) {
            if ( country1.getId().compareTo(new Long (3)) < 0){
                return country1.getId().compareTo(country2.getId());
            }
            return country1.getName().compareToIgnoreCase(country2.getName());
        }               
    }

    public List<Country> getCountries() {

        List<VisitorCountry> visitorCountries = profileDao.getAllCountries();       

        List<Country> countries = new ArrayList<Country>();
        for ( VisitorCountry country : visitorCountries){
            countries.add(country.getCountry());
        }

        Comparator<Country> comparator = new CountrySorter();       
        Collections.sort(countries, comparator);

        return countries;
    }

    public RegisterResponse registerVisitor(JsonVisitor visitorDetails){
        Visitor storedVisitor = (Visitor) sessionFactory.getCurrentSession().get(Visitor.class, visitorDetails.getTfscNumber(), LockMode.NONE);
        if ( storedVisitor == null){
            storedVisitor = new Visitor(visitorDetails);
        }else{
            storedVisitor.setVisitorDetails(visitorDetails);    
        }

        try{
            sessionFactory.getCurrentSession().saveOrUpdate(storedVisitor);

        }catch(Exception ex){
            return new RegisterResponse(false, "Failed To Register Card. Please Try Again Later.", visitorDetails);
        }

        return new RegisterResponse(true, "", visitorDetails);

    }
}

DAO 类的一点

@Service
@Transactional
public class ProfileDao {

    @Resource(name = "mySessionFactory")
    private SessionFactory sessionFactory;

    public List getAllCountries(){

        List<VisitorCountry> visitorCountries = sessionFactory.getCurrentSession()
        .getNamedQuery("GET_ALL_COUNTRIES").list();

        return visitorCountries;

    }

    public List<Retailer> getRetailerByRetailerNumber(String retailerNo) {

        List<Retailer> retailerByRetailerNumber = sessionFactory.getCurrentSession()
        .getNamedQuery("FindRetailerByRetailerNo").setString("retailerNo", retailerNo).list();

        return retailerByRetailerNumber;
    }

我的 application-context.xml 中有这个

and i have this in my application-context.xml

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

<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    <property name="hibernateProperties">
        <value>
            <![CDATA[
        hibernate.show_sql=true
        hibernate.format_sql=true
        hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
        ]]>
        </value>
    </property>
</bean>

谁能发现为什么我收到以下错误?

can anyone spot why i am getting the following error?

推荐答案

您使用 @Transactional 注释了 Dao 类,而不是您的服务类.行:

You annotated your Dao class with @Transactional, but not your service class. The line:

Visitor storedVisitor =
    (Visitor) sessionFactory.getCurrentSession().get(Visitor.class,
            visitorDetails.getTfscNumber(), LockMode.NONE);

要求您参与交易.

您可以通过向 ProfileService 类添加 @Transactional 注释或仅使用 registerVisitor() 方法来解决此问题.

You can fix this by adding the @Transactional annotation to your ProfileService class, or just the registerVisitor() method.

这篇关于Spring 和 hibernate:未找到当前线程的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 22:12