Невозможно сохранить данные в БД с использованием Spring 3.x и Hibernate 4.2.1.Final - PullRequest
0 голосов
/ 28 февраля 2019

Я получаю сообщение об ошибке при попытке сохранить данные в БД.

Я использую Spring 3.2.18.RELEASE и Hibernate 4.2.1.Final.

Я погуглил и нашел несколько ссылок SO ( Spring и hibernate: сеанс не найден для текущей темы ) и блогов (https://www.mkyong.com/spring/spring-hibernate-no-session-found-for-current-thread/)), а также проливает свет на ту же проблему, о которой я говорю. Но все эти ссылки используют аннотации для контроллеров, служби дао, в то время как мое приложение этого не делает.

Следовательно, я не мог найти решение относительно того, как настроить или исправить эту проблему, связанную с сеансом, с помощью чистого Spring XML configuration, так как я НЕ планирую обновиться до аннотаций в ближайшем будущем.будущее.

Тем не менее, я попробовал несколько изменений в моих DAO классах, и я заметил, что когда я изменяю с getCurrentSession() на openSession(), а затем flush() и close() session, он работает.

Поскольку я делаю Hibernate обновление в текущем проекте с 3.x до 4.x, будет много DAO классов, которые мне придется изменить (с getCurrentSession() на openSession()), чтобы заставить это работать.

здесь любое решение проблемы, с которой я столкнулся, где я мог бы продолжать использовать getCurrentSession()?

Ошибка:

[2019-02-27 17:23:21,902][USROUTER][http-nio-8080-exec-6][LinkSummaryDaoImpl.java:972][ERROR]- No Session found for current thread : 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:988)
    at com.demo.router.daoImpl.LinkSummaryDaoImpl.updateAuditLog(LinkSummaryDaoImpl.java:969)
    at com.demo.router.service.LinkSummaryServiceImpl.updateAuditLog(LinkSummaryServiceImpl.java:746)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy31.updateAuditLog(Unknown Source)
    at com.demo.router.controller.LoginController.handleRequest(LoginController.java:138)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy35.handleRequest(Unknown Source)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:933)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:867)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:951)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.demo.router.util.CrossScriptingFilter.doFilter(CrossScriptingFilter.java:27)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.demo.router.controller.SessionExpiredFilter.doFilter(SessionExpiredFilter.java:71)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

controllers.xml

<bean id="userlogin" class="com.demo.router.controller.LoginController">
    <property name="linkSummaryService">
        <ref bean="linkSummaryService"/>
    </property>
</bean>

services.xml

<bean id="linkSummaryService" class="com.demo.router.service.LinkSummaryServiceImpl">
    <property name="linkSummaryDaoImpl" ref="linkSummaryDaoImpl"/>
    <property name="currencyList">
        <ref bean="currencyList"/>
    </property>
</bean>

dao.xml

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>com/demo/router/persistence/ApplEodPrf.hbm.xml</value>
            <value>com/demo/router/persistence/LinkConfig.hbm.xml</value>
            <value>com/demo/router/persistence/LinkAppl.hbm.xml</value>
            <value>com/demo/router/persistence/RterAudtLog.hbm.xml</value>
            <value>com/demo/router/persistence/MsgCntl.hbm.xml</value>
            <value>com/demo/router/persistence/MsgRte.hbm.xml</value>
            <value>com/demo/router/persistence/Currency.hbm.xml</value>
            <value>com/demo/router/persistence/LinkOperCmnt.hbm.xml</value>
            <value>com/demo/router/persistence/MessageType.hbm.xml</value>
            <value>com/demo/router/persistence/MsgErr.hbm.xml</value>
            <value>com/demo/router/persistence/MsgPrblmType.hbm.xml</value>
            <value>com/demo/router/persistence/MsgRcrdSts.hbm.xml</value>
            <value>com/demo/router/persistence/MsgTx.hbm.xml</value>
            <value>com/demo/router/persistence/PrblmQuItem.hbm.xml</value>
            <value>com/demo/router/persistence/ReceivingApplCnctSts.hbm.xml</value>
            <value>com/demo/router/persistence/ReceivingApplMtrc.hbm.xml</value>
            <value>com/demo/router/persistence/RterAudtCat.hbm.xml</value>
            <value>com/demo/router/persistence/SndApplMtrc.hbm.xml</value>
            <value>com/demo/router/persistence/SQLQuery.hbm.xml</value>
            <value>com/demo/router/persistence/MsgCntlHist.hbm.xml</value>
            <value>com/demo/router/persistence/MsgTxHist.hbm.xml</value>
            <value>com/demo/router/persistence/ApplSnderTrgrCntl.hbm.xml</value>
            <value>com/demo/router/persistence/BatApplFileCntl.hbm.xml</value>
            <value>com/demo/router/persistence/OtbMsgCntl.hbm.xml</value>
            <value>com/demo/router/persistence/OtbMsgTx.hbm.xml</value>
            <value>com/demo/router/persistence/OtbMsgCntlHist.hbm.xml</value>
            <value>com/demo/router/persistence/OtbMsgTxHist.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.query.factory_class">
                org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
            </prop>
            <prop key="hibernate.c3p0.acquire_increment">1</prop>
            <prop key="hibernate.c3p0.max_size">80</prop>
            <prop key="hibernate.c3p0.min_size">20</prop>
            <prop key="hibernate.c3p0.initial_pool_size">10</prop>
            <prop key="hibernate.c3p0.min_pool_size">5</prop>
            <prop key="hibernate.c3p0.max_pool_size">15</prop>
            <prop key="hibernate.c3p0.timeout">1800</prop>
            <prop key="hibernate.c3p0.max_statements">50</prop>
        </props>
    </property>
</bean>

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

<bean id="routerDAOImpl" class="com.demo.router.daoImpl.RouterDAOImpl">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
    <property name="usrouterPackage">
        <value>${application.usrtPackage.name.value}</value>
    </property>
    <property name="messageSummaryFetchSize">
        <value>${application.messageSummaryFetchSize.name.value}</value>
    </property>
</bean>

<bean id="linkSummaryDaoImpl" class="com.demo.router.daoImpl.LinkSummaryDaoImpl">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
    <property name="usrouterPackage">
        <value>${application.usrtPackage.name.value}</value>
    </property>
</bean> 

LoginController.java

public class LoginController implements Controller {    

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //login the current user here
        doLogin();
        //audit now
        this.linkSummaryService.updateAuditLog(rterAudtLog);
    }

}

LinkSummaryServiceImpl.java

public class LinkSummaryServiceImpl implements LinkSummaryService {

    @Transactional 
    public void updateAuditLog(RterAudtLog rterAudtLog) throws JPMCDAOException {
        this.linkSummaryDaoImpl.updateAuditLog(rterAudtLog);
    }

}

LinkSummaryDaoImpl.java

public class LinkSummaryDaoImpl implements LinkSummaryDao {
    public void updateAuditLog(RterAudtLog rterAudtLog) throws JPMCDAOException {
        Session session = null;
        try {
            session = this.sessionFactory.getCurrentSession();
            //session = this.sessionFactory.openSession(); // WORKS
            session.save(rterAudtLog);
        } catch (HibernateException he) {
            log.error(he.getMessage() + " : " + CommonUtils.exceptionToString(he));
            throw new JPMCDAOException("Hibernate Exception :" + he.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage() + " : " + CommonUtils.exceptionToString(e));
            throw new JPMCDAOException("Unexpected Exception :" + e.getMessage());
        }
        /* WORKS 
        finally {
            if (null != session) {
                session.flush();
                session.close();
            }
        }
        */
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...