spring - OpenEntityManagerInViewFilter closed session before database update -
i set openentitymanagerinviewfilter,but close session before writting database.here code ,please me.thank .
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="webapp_id" version="2.5"> <display-name>panshi</display-name> <context-param> <description>服务器的参数!</description> <param-name>webapprootkey</param-name> <param-value>webroot.root</param-value> </context-param> <context-param> <param-name>contextconfiglocation</param-name> <param-value> /web-inf/spring/*-config.xml </param-value> </context-param> <context-param> <description>日志的参数。</description> <param-name>log4jconfiglocation</param-name> <param-value>/web-inf/log/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.log4jconfiglistener</listener-class> </listener> <listener> <listener-class> org.springframework.security.web.session.httpsessioneventpublisher </listener-class> </listener> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/picshow/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/css/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/images/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <filter> <filter-name>httpmethodfilter</filter-name> <filter-class>org.springframework.web.filter.hiddenhttpmethodfilter</filter-class> </filter> <filter-mapping> <filter-name>httpmethodfilter</filter-name> <servlet-name>spring</servlet-name> </filter-mapping> <filter> <filter-name>springsecurityfilterchain</filter-name> <filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter-mapping> <filter-name>springsecurityfilterchain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <session-config> <session-timeout>10</session-timeout> </session-config> <error-page> <exception-type>java.lang.exception</exception-type> <!-- displays stack trace --> <location>/web-inf/jsp/uncaughtexception.jsp</location> </error-page> <filter> <filter-name>setcharacterencoding</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceencoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>setcharacterencoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>entitymanagerfilter</filter-name> <filter-class>org.springframework.orm.jpa.support.openentitymanagerinviewfilter</filter-class> </filter> <filter-mapping> <filter-name>entitymanagerfilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>entitymanagerfilter</filter-name> <url-pattern>*.json</url-pattern> </filter-mapping> <!-- <filter> <filter-name>hibernatefilter</filter-name> <filter-class> org.springframework.orm.hibernate4.support.opensessioninviewfilter </filter-class> </filter> <filter-mapping> <filter-name>hibernatefilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>hibernatefilter</filter-name> <url-pattern>*.json</url-pattern> </filter-mapping> --> <welcome-file-list> <welcome-file>/index.html</welcome-file> </welcome-file-list> </web-app>
jpa setting
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config /> <bean class="org.springframework.orm.jpa.support.persistenceannotationbeanpostprocessor"/> <context:component-scan base-package="cn.hballsoft.domain" /> <context:component-scan base-package="cn.hballsoft.security.domain" /> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close" p:driverclassname="${jdbc.driverclassname}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 这里多部分文件上传处理控制器 --> <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="maxuploadsize" value="10000000" /> </bean> <!-- jpa entitymanagerfactory --> <bean id="jpadialect" class="org.springframework.orm.jpa.vendor.hibernatejpadialect" /> <bean id="jpavendoradapter" class="org.springframework.orm.jpa.vendor.hibernatejpavendoradapter" /> <!-- jpa primary entitymanagerfactory entitymanagerfactory--> <bean id="entitymanagerfactory" lazy-init="true" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean" p:persistenceunitname="serverpu" p:jpavendoradapter-ref="jpavendoradapter" p:jpadialect-ref="jpadialect" p:datasource-ref="datasource" /> <bean id="sessionfactory" factory-bean="entitymanagerfactory" factory-method="getsessionfactory"> </bean> <bean id="transactionmanager" class="org.springframework.orm.jpa.jpatransactionmanager" p:entitymanagerfactory-ref="entitymanagerfactory" /> <tx:annotation-driven transaction-manager="transactionmanager" /> <bean id="departmentdao" class="cn.hballsoft.domain.dao.imagedao"/> <bean id="userdao" class="cn.hballsoft.security.domain.userdao"/> <bean id="roledao" class="cn.hballsoft.security.domain.roledao"/> <bean id="resourcedao" class="cn.hballsoft.security.domain.resourcedao"> <qualifier value="resourcedao"/> </bean> </beans>
persistence
<?xml version="1.0" encoding="utf-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="serverpu" transaction-type="resource_local"> <!-- resource_local --> <provider>org.hibernate.ejb.hibernatepersistence</provider> <!-- <class>cn.hballsoft.domain.category</class>--> <class>cn.hballsoft.security.domain.resource</class> <class>cn.hballsoft.security.domain.role</class> <class>cn.hballsoft.security.domain.user</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.mysql5dialect" /> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.nocacheprovider" /> <property name="hibernate.showsql" value="true" /> <property name="hibernate.cache.use_second_level_cache" value="false" /> <property name="hibernate.search.default.directory_provider" value="org.hibernate.search.store.fsdirectoryprovider" /> <property name="hibernate.search.default.indexbase" value="d:/indexes" /> </properties> </persistence-unit> </persistence>
****dao******
@repository @transactional public class resourcedao {
public static final string type = "type"; @persistencecontext private entitymanager entitymanager; @transactional public void save(resource entity) { entitymanagerhelper.log("saving resource instance", level.info, null); try { entitymanager.persist(entity); entitymanagerhelper.log("save successful", level.info, null); } catch (runtimeexception re) { entitymanagerhelper.log("save failed", level.error, re); throw re; } } }
*********method in controller
@transactional @requestmapping(value="/admin/manage/resource.json",method = requestmethod.post) @responsebody public linkedhashmap<string, object> createresource(@requestbody resource resource){ resource res = new resource(resource.getresourcestring()); res.setdescn(resource.getdescn()); res.setmethod(resource.getmethod()); res.settype(resource.gettype()); res.setpriority(resource.getpriority()); resourcedao.save(res); if(!res.getid().isempty()){ return buildmessageresult(true,"成功建立资源"+res.getid());} else{ return buildmessageresult(true,"建立资源失败!"); } }
****debug console output **************
09-04 17:59:32 debug requestmappinghandlermapping:220 - looking handler method path /admin/manage/resource.json 09-04 17:59:32 debug requestmappinghandlermapping:264 - found 1 matching mapping(s) [/admin/manage/resource.json] : [{[/admin/manage/resource.json],methods=[post],params=[],headers=[],consumes=[],produces=[],custom=[]}] 09-04 17:59:32 debug handlermethod:135 - method [initbinder] returned [null] 09-04 17:59:32 debug handlermethod:129 - invoking [createresource] method arguments [cn.hballsoft.security.domain.resource@56ad4264] 09-04 17:59:32 info serverpu:60 - saving resource instance 09-04 17:59:32 debug transactionsynchronizationmanager:140 - retrieved value [org.springframework.orm.jpa.entitymanagerholder@1a08777c] key [org.springframework.orm.jpa.localcontainerentitymanagerfactorybean@529e0c79] bound thread [http-8080-2] 09-04 17:59:32 debug abstractsaveeventlistener:130 - generated identifier: 40288ae840e869000140e869a3f90000, using strategy: org.hibernate.id.uuidhexgenerator 09-04 17:59:32 info serverpu:60 - save successful 09-04 17:59:32 debug handlermethod:135 - method [createresource] returned [{success=true, message=成功建立资源40288ae840e869000140e869a3f90000}] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.modelandviewmethodreturnvaluehandler@e58ff51] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.method.annotation.modelmethodprocessor@2b39d891] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.viewmethodreturnvaluehandler@6b6b4e30] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.httpentitymethodprocessor@59fcadd3] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.callablemethodreturnvaluehandler@31ccbefe] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.deferredresultmethodreturnvaluehandler@53e64a3b] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.asynctaskmethodreturnvaluehandler@70f87478] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.method.annotation.modelattributemethodprocessor@f74f6ef] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug handlermethodreturnvaluehandlercomposite:78 - testing if return value handler [org.springframework.web.servlet.mvc.method.annotation.requestresponsebodymethodprocessor@47ffccd6] supports [java.util.linkedhashmap<java.lang.string, java.lang.object>] 09-04 17:59:32 debug requestresponsebodymethodprocessor:150 - written [{success=true, message=成功建立资源40288ae840e869000140e869a3f90000}] "application/json;charset=utf-8" using [org.springframework.http.converter.json.mappingjacksonhttpmessageconverter@34a8a271] 09-04 17:59:32 debug dispatcherservlet:999 - null modelandview returned dispatcherservlet name 'spring': assuming handleradapter completed request handling 09-04 17:59:32 debug dispatcherservlet:1028 - cleared thread-bound request context: firewalledrequest[ org.apache.catalina.connector.requestfacade@40545646] 09-04 17:59:32 debug dispatcherservlet:966 - completed request 09-04 17:59:32 debug xmlwebapplicationcontext:332 - publishing event in webapplicationcontext namespace 'spring-servlet': servletrequesthandledevent: url=[/panshi/admin/manage/resource.json]; client=[127.0.0.1]; method=[post]; servlet=[spring]; session=[1ac287b1ebe796642f17b9ab4f9b6d8a]; user=[null]; time=[96ms]; status=[ok] 09-04 17:59:32 debug xmlwebapplicationcontext:332 - publishing event in root webapplicationcontext: servletrequesthandledevent: url=[/panshi/admin/manage/resource.json]; client=[127.0.0.1]; method=[post]; servlet=[spring]; session=[1ac287b1ebe796642f17b9ab4f9b6d8a]; user=[null]; time=[96ms]; status=[ok] 09-04 17:59:32 debug transactionsynchronizationmanager:243 - removed value [org.springframework.orm.jpa.entitymanagerholder@1a08777c] key [org.springframework.orm.jpa.localcontainerentitymanagerfactorybean@529e0c79] thread [http-8080-2] 09-04 17:59:32 debug openentitymanagerinviewfilter:188 - closing jpa entitymanager in openentitymanagerinviewfilter 09-04 17:59:32 debug entitymanagerfactoryutils:338 - closing jpa entitymanager 09-04 18:09:59 debug httpsessioneventpublisher:83 - publishing event: org.springframework.security.web.session.httpsessiondestroyedevent[source=org.apache.catalina.session.standardsessionfacade@75f10df7] 09-04 18:09:59 debug xmlwebapplicationcontext:332 - publishing event in root webapplicationcontext: org.springframework.security.web.session.httpsessiondestroyedevent[source=org.apache.catalina.session.standardsessionfacade@75f10df7] 09-04 18:09:59 debug defaultlistablebeanfactory:246 - returning cached instance of singleton bean 'org.springframework.security.core.session.sessionregistryimpl#0' 09-04 18:09:59 debug defaultlistablebeanfactory:246 - returning cached instance of singleton bean 'loggerlistener'
in testcase , works fine , write database well.
@runwith(springjunit4classrunner.class) @contextconfiguration("jpa-config.xml") @transactionconfiguration(transactionmanager="transactionmanager", defaultrollback=false) @transactional public class testjpa { applicationcontext ctx; datasource datasource; @beforetransaction public void verifyinitialdatabasestate() { ctx = new filesystemxmlapplicationcontext("e:/fbworkspace/panshi/webcontent/web-inf/spring/jpa-config.xml"); datasource = (datasource)ctx.getbean("datasource"); } @before public void setuptestdatawithintransaction() { // set test data within transaction } @test // overrides class-level defaultrollback setting @rollback(false) public void modifydatabasewithintransaction() { resource res = new resource("teset resource"); resourcedao resdao = (resourcedao)ctx.getbean("resourcedao"); resdao.save(res); } @after public void teardownwithintransaction() { // execute "tear down" logic within transaction } @aftertransaction public void verifyfinaldatabasestate() { // logic verify final state after transaction has rolled } }
************output test *************
09-04 18:44:05 debug entitymanagerfactoryregistry:66 - registering entitymanagerfactory: serverpu 09-04 18:44:05 warn entitymanagerfactoryregistry:80 - hhh000436: entity manager factory name (serverpu) registered. if entity manager clustered or passivated, specify unique value property 'hibernate.ejb.entitymanager_factory_name' 09-04 18:44:05 info serverpu:60 - saving resource instance 09-04 18:44:05 debug transactionsynchronizationmanager:140 - retrieved value [org.springframework.orm.jpa.entitymanagerholder@4b5a142f] key [org.springframework.orm.jpa.localcontainerentitymanagerfactorybean@6e3404f] bound thread [main] [org.springframework.transaction.support.defaulttransactionstatus@54eeabe8]; rollback [false] 09-04 18:44:05 debug jpatransactionmanager:923 - triggering beforecommit synchronization 09-04 18:44:05 debug jpatransactionmanager:936 - triggering beforecompletion synchronization 09-04 18:44:05 debug jpatransactionmanager:753 - initiating transaction commit 09-04 18:44:05 debug jpatransactionmanager:508 - committing jpa transaction on entitymanager [org.hibernate.ejb.entitymanagerimpl@62c37f31] 09-04 18:44:05 debug abstracttransactionimpl:173 - committing 09-04 18:44:05 debug jdbctransaction:113 - committed jdbc connection 09-04 18:44:05 debug jdbctransaction:126 - re-enabling autocommit 09-04 18:44:05 debug dirtiescontexttestexecutionlistener:107 - after test method: context [[testcontext@2f8bbc98 testclass = testjpa, testinstance = cn.hballsoft.test.testjpa@6ba7508a, testmethod = modifydatabasewithintransaction@testjpa, testexception = [null], mergedcontextconfiguration = [mergedcontextconfiguration@3598cb3d testclass = testjpa, locations = '{classpath:/cn/hballsoft/test/jpa-config.xml}', classes = '{}', contextinitializerclasses = '[]', activeprofiles = '{}', contextloader = 'org.springframework.test.context.support.delegatingsmartcontextloader', parent = [null]]]], class dirties context [false], class mode [null], method dirties context [false]. 09-04 18:44:05 info genericapplicationcontext:1042 - closing org.springframework.context.support.genericapplicationcontext@4cf7c31d: startup date [wed sep 04 18:43:59 cst 2013]; root of context hierarchy 09-04 18:44:05 debug genericapplicationcontext:332 - publishing event in org.springframework.context.support.genericapplicationcontext@4cf7c31d: org.springframework.context.event.contextclosedevent[source=org.springframework.context.support.genericapplicationcontext@4cf7c31d: startup date [wed sep 04 18:43:59 cst 2013]; root of context hierarchy] 09-04 18:44:05 debug defaultlistablebeanfactory:246 - returning cached instance of singleton bean 'lifecycleprocessor' 09-04 18:44:05 info defaultlistablebeanfactory:444 - destroying singletons in org.springframework.beans.factory.support.defaultlistablebeanfactory@62770d2e: defining beans 09-04 18:44:05 debug disposablebeanadapter:226 - invoking destroy() on bean name 'entitymanagerfactory' 09-04 18:44:05 info localcontainerentitymanagerfactorybean:441 - closing jpa entitymanagerfactory persistence unit 'serverpu' 09-04 18:44:05 debug sessionfactoryimpl:1369 - hhh000031: closing 09-04 18:44:05 debug entitymanagerfactoryregistry:108 - remove: name=serverpu 09-04 18:44:05 debug disposablebeanadapter:302 - invoking destroy method 'close' on bean name 'datasource'
i know happen. have multiple *-config.xml of them have
<context:annotation-config /> <context:component-scan base-package="cn.hballsoft.domain" /> <context:component-scan base-package="cn.hballsoft.security.domain" />
maybe cause duplicate load transaction config.
keep single , slove problem.
Comments
Post a Comment