Concurrent requests adding the same session attribute result in duplicate key constraint violation
We are using Spring session 2.0.5.RELEASE. We are using JDBC session persistence. We have migrated those applications that were previously using container in memory session (Wildfly/Undertow). The code has stayed as-is.
We have html pages that fire up multiple calls in AJAX simultaneously to a controller. In the controller we have code that set an attribute into the session.
The issue is that multiple threads of the application server are busy in parallel treating those AJAX calls, the first thread will insert the new attribute in the database. The other threads are then supposed to call an update of the attribute in the database because the attribute already exists. But the issue is that the other threads have not detected (yet) that the attribute already exists and try to do an insert as well resulting in a duplicate key exception.
I must say that as a workaround we have patched the application to do a sort of initialisation AJAX call at page load and this initialisation just set the attribute with a blank value, this allows the attribute row to be created and when further calls are being made in parallel, the JDBC implementation of Spring session sees that only updates are needed.
However I wanted to report this in order to support those use cases natively (without workarounds) using JDBC persistence.
Thanks for the report @ovanekem. This is a duplicate of #1031 which has been resolved in 2.1.0.M2 and backported to 2.0.6.RELEASE via #1151.
Duplicate of #1031
I think I incorrectly labeled this as duplicate of #1031 while in fact it is a different problem - apologies for that @ovanekem.
Can you provide a stack trace, or even better, a minimal sample to reproduce the problem? Also can you take a look at #1216 and see whether that appears to be the same problem?
@vpavic I'll try to create a sample project this weekend that reproduces the issue.
@vpavic I now have created some test cases that reproduce the issue. Attached is a ZIP file that contains the project. It is a Spring MVC project running on Wildfly and using Spring session with JDBC persistence. There are prepared Docker containers so that you do not have to install Wildfly,... One container for wildfly (and the application) and one container with postgresql configured for the session persistence. You can start the docker-compose.yml and it should start seamlessly. When started, go to http://localhost/test/main. You will see an HTML page with 4 buttons: initialize (the HTTP session), call AJAX 20 times asynchronously, call AJAX 20 times synchronously, invalidate (the session). You can try by clicking on initialize and it will call a controller that just creates the web session (request.getSession(true)). Then when you try calling the AJAX controller 20 times ASYNCHRONOUSLY you will normally get a few HTTP 500. On the console of the wildly container you will clearly see the exception:
test-app | at java.lang.Thread.run(Thread.java:748) test-app | Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk" test-app | Detail: Key (session_primary_id, attribute_name)=(2d716b1a-94a6-4041-ba40-a3428204f115, numberOfCalls) already exists. test-app | at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2310) test-app | at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2023) test-app | at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217) test-app | at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421) test-app | at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:166)
You can also see that doing the same REST calls without the asynchronous flag, we do not have an issue. Hope you can run this sample and that it helps you in the investigation.
Regards
Olivier test-spring-session-ajax.zip
Thanks for following up and providing the sample @ovanekem - I now have the understanding of what's going on.
After giving this issue some thought recently, I'm afraid this is a difficult problem to address without making some compromises in other places.
We've done quite a few optimizations to JdbcOperationsSessionRepository, largely thanks to the feedback from our community, however relational database as the underlying session store will always be limited compared to stores like Redis or Hazelcast. Part of this is due to the fact that with relational database we use different command (INSERT vs UPDATE) depending whether the attribute is already present or not. In a highly concurrent system, race conditions are bound to happen, and this is where the limitation of case when we're saving the attribute that's not already present (i.e. the INSERT scenario) comes to play.
Typically, you can address a problem like this in two ways:
- locking mechanism - this isn't a viable option for Spring Session, as we'd need to use distributed lock which would have a degrading effect on performance
- introduce error handling mechanism - this could be acceptable option, but it raises other concerns:
- in order to do so, we would have to drop our JDBC batching optimization for
INSERTs - when we catch the
DuplicateKeyException, do we have enough knowledge to determine what to do:- log the exception and carry on - this means we assume the other request that managed to do
INSERThas the actual attribute value - transform
INSERTstatement toUPDATE- this means we assume our attribute value is actual and we overwrite the other request
- log the exception and carry on - this means we assume the other request that managed to do
- in order to do so, we would have to drop our JDBC batching optimization for
Do you have any thoughts on this @rwinch?
It's also worth noting that in some cases these problems can be address in application logic - see #1216 reported by @bonhamcm and in particular this comment.
Could you add an option to perform a merge or upsert depending on the database? You can use INSERT INTO ... ON CONFLICT UPDATE in PostgresSQL 9.5+:
https://www.postgresql.org/docs/9.5/static/sql-insert.html
We are trying to stick with standard SQL for obvious reasons. There is JdbcOperationsSessionRepository#setCreateSessionAttributeQuery (and equivalents for other cases) available to provide custom SQL - that could indeed be used as a workaround.
We just upgraded and are getting the error below. We have the following from Spring:
Spring Core: 5.0.5.RELEASE Spring Security: 5.1.1.RELEASE Spring Session: 2.1.2.RELEASE
[o.s.j.s.SQLErrorCodesFactory] [http-nio-127.0.0.1-11450-exec-9]: SQLErrorCodes loaded: [DB2, Derby, H2, HDB, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase] [o.a.c.c.C.[.[.[.[default]] [http-nio-127.0.0.1-11450-exec-9]: Servlet.service() for servlet [default] in context with path [] threw exception org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated ; nested exception is java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:905) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:547) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:135) at org.springframework.session.jdbc.JdbcOperationsSessionRepository$3.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:442) at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:421) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:135) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:240) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:201) at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:154) at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1156) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495) 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) Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494) at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780) at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343) at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3865) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3845) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1061) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384) at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:855) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ... 34 common frames omitted Caused by: oracle.jdbc.OracleDatabaseException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498) ... 51 common frames omitted 2018-12-13 12:18:24,089 ERROR [o.a.c.c.C.[.[.[.[jsp]] [http-nio-127.0.0.1-11450-exec-9]: Servlet.service() for servlet jsp threw exception oracle.jdbc.OracleDatabaseException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498) at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780) at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343) at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3865) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3845) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1061) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384) at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:855) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:905) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:547) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:135) at org.springframework.session.jdbc.JdbcOperationsSessionRepository$3.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:442) at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:421) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:135) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:240) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:201) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper$SessionCommittingRequestDispatcher.include(SessionRepositoryFilter.java:443) at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:884) at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:679) at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:673) at org.apache.tiles.request.jsp.JspRequest.doInclude(JspRequest.java:123) at org.apache.tiles.request.AbstractViewRequest.dispatch(AbstractViewRequest.java:47) at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47) at org.apache.tiles.request.render.ChainedDelegateRenderer.render(ChainedDelegateRenderer.java:68) at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259) at org.apache.tiles.TilesContainerWrapper.render(TilesContainerWrapper.java:108) at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:188) at org.apache.tiles.template.InsertAttributeModel.execute(InsertAttributeModel.java:132) at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:299) at org.apache.jsp.WEB_002dINF.jsp.layout.main_005flayout_jsp._jspx_meth_tiles_005finsertAttribute_005f0(main_005flayout_jsp.java:677) at org.apache.jsp.WEB_002dINF.jsp.layout.main_005flayout_jsp._jspService(main_005flayout_jsp.java:203) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:138) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:716) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:468) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper$SessionCommittingRequestDispatcher.forward(SessionRepositoryFilter.java:437) at org.apache.tiles.request.servlet.ServletRequest.forward(ServletRequest.java:265) at org.apache.tiles.request.servlet.ServletRequest.doForward(ServletRequest.java:228) at org.apache.tiles.request.AbstractClientRequest.dispatch(AbstractClientRequest.java:57) at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47) at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259) at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:397) at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:238) at org.apache.tiles.TilesContainerWrapper.render(TilesContainerWrapper.java:103) at org.apache.tiles.impl.mgmt.CachingTilesContainer.render(CachingTilesContainer.java:126) at org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:158) at org.apache.struts2.result.StrutsResultSupport.execute(StrutsResultSupport.java:204) at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:375) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:279) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:179) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:49) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:142) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:137) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:137) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:201) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:160) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:175) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.etouchpoint.components.querybar.ui.QueryBarInterceptor.intercept(QueryBarInterceptor.java:210) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.etouchpoint.common.web.struts2.SpringSecurityUserAwareInterceptor.intercept(SpringSecurityUserAwareInterceptor.java:45) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.etouchpoint.common.web.struts2.TransactionInterceptor.intercept(TransactionInterceptor.java:49) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:167) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:137) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:101) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.CookieInterceptor.intercept(CookieInterceptor.java:261) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:67) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:85) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:121) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:203) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:196) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:48) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:574) at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79) at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:151) at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:716) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:468) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318) at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:442) at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:379) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:176) at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1156) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495) 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) 2018-12-13 12:18:24,136 ERROR [o.a.c.c.C.[.[.[.[default]] [http-nio-127.0.0.1-11450-exec-9]: Servlet.service() for servlet default threw exception org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated ; nested exception is java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:905) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:547) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:135) at org.springframework.session.jdbc.JdbcOperationsSessionRepository$3.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:442) at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:421) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:135) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:240) at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:201) at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:154) at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:716) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:468) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318) at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:442) at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:379) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:176) at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1156) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495) 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) Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494) at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780) at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343) at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3865) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3845) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1061) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384) at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:855) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ... 37 common frames omitted Caused by: oracle.jdbc.OracleDatabaseException: ORA-00001: unique constraint (SPRING_SESSION_ATTRIBUTES_PK) violated at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498) ... 54 common frames omitted
I know you are trying to reduce the number of SQL queries for performance reasons. Looking at the code where we are getting the Exception from:
`private void insertSessionAttributes(JdbcSession session, List
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
String attributeName = attributeNames.get(i);
ps.setString(1, attributeName);
setObjectAsBlob(ps, 2, session.getAttribute(attributeName));
ps.setString(3, session.getId());
}
@Override
public int getBatchSize() {
return attributeNames.size();
}
});
}
else {
// Exception is thrown from this command this.jdbcOperations.update(this.createSessionAttributeQuery, (ps) -> { String attributeName = attributeNames.get(0); ps.setString(1, attributeName); setObjectAsBlob(ps, 2, session.getAttribute(attributeName)); ps.setString(3, session.getId()); }); } }`
Unless you do an "Insert or Update" type statement here; you pretty much have to either
- Catch the exception and then do an update, or ignore.
- Check to ensure the row does not exist before inserting.
If you can do "Insert or Update" great! But you may have to go the route of catching, or checking.
Thanks for following up on this issue @pminearo.
As explained in my previous comment, neither of the options is ideal and presents a certain compromise. That's why I'm hesitant to do any of those changes as we would negate some of the optimization efforts that have been made to JdbcOperationsSessionRepository.
Is there anything you could do on application level in order to reduce the likelihood of concurrent requests that operate on the same session attribute?
Unfortunately no, it is out of our hands with when AJAX calls get made. We use a product called SmartClient on the front end and don't have much control over when it makes the calls. Plus, having sites ensure only 1 AJAX call is made at a time defeats a lot of the performance gains from making multiple calls at the same time.
Since the exception is caught and logged anyways; why would catching an exception and ignoring it be a compromise to performance? Wouldn't that be a slightly better performance because it is not getting logged which slows the performance? Could it be assumed that if Spring Session tries to insert an attribute that already exists; it has the same attribute value? I do not know what is actually being stored, but I would think it would be the same thing. If it is the same BLOB being stored, you could just ignore the exception? If you are worried about not showing an error, you could catch and log as Debug; that way if there is a problem we could turn on Debug Logging and see what it is.
The problem we have is we have no control over the logging of the error. This is done in Tomcat. Which, sets off our alerting system ; sending out false-positives.
Could it be assumed that if Spring Session tries to insert an attribute that already exists; it has the same attribute value?
That seems like a more likely of the two error handling scenarios described in my previous comment, however to implement that we'd have to drop our batching optimization.
On my side, we indeed solved this from an application point of view. But also in my case I have full control on the client code (which not seems to be the case of @pminearo ). Coming back to the roots of this issue, this is in fact bad design in the first place (as was also in our application) that there are multiple AJAX calls at once to store a value in a session variable with different values. Indeed, nothing can be predictable from a browser perspective that one call will really be executed before another (depends largely on how the server will handle thread pooling,...).
With this in mind, I think a potential workaround implemented in the framework directly would be to do an update when the insert fails. I do not think (but I have not tested ;-)). The risk of course is that the AJAX calls that did the insert in the first place was supposed to come second and this value will be erased, but this is a consequence of the initial bad design I guess. Now we need to check that this does not indeed fails the batch optimization.
A quick update:
I pulled down the 2.1.2.RELEASE tag of the cod base. I then edited JdbcOperationsSessionRepository.insertSessionAttributes() to have a try/catch around the 'if/else' statement. Then logged what info I had. What's interesting about the output right now is the only Attribute Name listed was "SPRING_SECURITY_CONTEXT". Even though, when I look in the DB; I see multiple attributes for that user's session. The exception does happen right after they log in; which would make sense as to why there is only 1 attribute being inserted. So, far this quick hack is not causing any side affects. But that does not mean there aren't any. Just means I haven't seen, or heard, any. I will give you more updates as I see them.
I encountered a similar stack on 2.1.2:
In happens in the context of spring-oauth2
ERROR (PSQLException): Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?]; ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk" Detail: Key (session_primary_id, attribute_name)=(cde0debe-e6f4-460b-990c-d126ef0c79ae,
org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST) already exists.; nested exception is org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk"
Detail: Key (session_primary_id, attribute_name)=(cde0debe-e6f4-460b-990c-d126ef0c79ae, org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST) already exists.] with root cause
ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk"
Key (session_primary_id, attribute_name)=(cde0debe-e6f4-460b-990c-d126ef0c79ae, org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST) already exists.
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk"
Detail: Key (session_primary_id, attribute_name)=(cde0debe-e6f4-460b-990c-d126ef0c79ae, org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST) already exists.
at QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at QueryExecutorImpl.execute(QueryExecutorImpl.java:481)
at PgStatement.executeBatch(PgStatement.java:840)
at PgPreparedStatement.executeBatch(PgPreparedStatement.java:1538)
at DelegatingStatement.executeBatch(DelegatingStatement.java:223)
at DelegatingStatement.executeBatch(DelegatingStatement.java:223)
at JdbcTemplate.lambda$batchUpdate$2(JdbcTemplate.java:950)
at JdbcTemplate.execute(JdbcTemplate.java:617)
at JdbcTemplate.execute(JdbcTemplate.java:646)
at JdbcTemplate.batchUpdate(JdbcTemplate.java:936)
at JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:529)
at JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:135)
at JdbcOperationsSessionRepository$3.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:442)
at TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
at TransactionTemplate.execute(TransactionTemplate.java:140)
at JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:421)
at JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:135)
at SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:240)
at SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:201)
at SessionRepositoryFilter$SessionRepositoryResponseWrapper.onResponseCommitted(SessionRepositoryFilter.java:189)
at OnCommittedResponseWrapper.doOnResponseCommitted(OnCommittedResponseWrapper.java:227)
at OnCommittedResponseWrapper.sendRedirect(OnCommittedResponseWrapper.java:127)
I initially felt it might be related to #1031 but @vpavic suggests my case might rather be related to this ticket. Given this (production) stack, do you feel this is the same issue ? (I'm not able to pronounce myself). If no, I shall create a dedicated ticket but I doubt I will be able to provide a reproduction case.
I have a same issue in 2.1.4 with remote H2 too:
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?]; Unique index or primary key violation: "PRIMARY_KEY_B ON PUBLIC.SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME) VALUES ('2e8d8901-067c-4e98-aa7b-8feb240cd71c', 'SPRING_SECURITY_SAVED_REQUEST', 8)"; SQL statement:
INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ? [23505-197]; nested exception is org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY_KEY_B ON PUBLIC.SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME) VALUES ('2e8d8901-067c-4e98-aa7b-8feb240cd71c', 'SPRING_SECURITY_SAVED_REQUEST', 8)"; SQL statement:
INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ? [23505-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.index.BaseIndex.getDuplicateKeyException(BaseIndex.java:101)
at org.h2.mvstore.db.MVSecondaryIndex.requireUnique(MVSecondaryIndex.java:236)
at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:202)
at org.h2.mvstore.db.MVTable.addRow(MVTable.java:732)
at org.h2.command.dml.Insert.addRowImpl(Insert.java:237)
at org.h2.command.dml.Insert.insertRows(Insert.java:204)
at org.h2.command.dml.Insert.update(Insert.java:134)
at org.h2.command.CommandContainer.update(CommandContainer.java:102)
at org.h2.command.Command.executeUpdate(Command.java:261)
at org.h2.server.TcpServerThread.process(TcpServerThread.java:399)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:165)
at java.base/java.lang.Thread.run(Thread.java:834)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1444)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:917)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:547)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:135)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository$3.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:442)
at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:421)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:135)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:240)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:201)
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:154)
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.cloud.sleuth.instrument.web.ExceptionLoggingFilter.doFilter(ExceptionLoggingFilter.java:50)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at brave.servlet.TracingFilter.doFilter(TracingFilter.java:69)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:461)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:394)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:253)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:348)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:173)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY_KEY_B ON PUBLIC.SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME) VALUES ('2e8d8901-067c-4e98-aa7b-8feb240cd71c', 'SPRING_SECURITY_SAVED_REQUEST', 8)"; SQL statement:
INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ? [23505-197]
at org.h2.engine.SessionRemote.done(SessionRemote.java:623)
at org.h2.command.CommandRemote.executeUpdate(CommandRemote.java:237)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:199)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:153)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:867)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617)
... 41 common frames omitted
- Catch the exception and then do an update, or ignore. I think this could be a good solution.
I have same issue with version 2.1.7.
We have same issue with version 2.1.7.
PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_FRONT_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION_FRONT WHERE SESSION_ID = ?]; Duplicate entry '25809e1f-9d04-4d61-8a91-c114db44e398-getCartInfoResponse' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '25809e1f-9d04-4d61-8a91-c114db44e398-getCartInfoResponse' for key 'PRIMARY' Handler: public com.drybit.shade.frontend.controller.ajax.addtocart.AddToCartResult com.drybit.shade.frontend.controller.ajax.addtocart.AjaxAddToCartController.addToCart(int,java.lang.Integer) throws com.drybit.shade.frontend.exception.ShopException
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_FRONT_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION_FRONT WHERE SESSION_ID = ?]; Duplicate entry '25809e1f-9d04-4d61-8a91-c114db44e398-getCartInfoResponse' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '25809e1f-9d04-4d61-8a91-c114db44e398-getCartInfoResponse' for key 'PRIMARY'
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1442)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:861)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:916)
Here's the query I'm using with the JdbcOperationsSessionRepository#setCreateSessionAttributeQuery approach with my Oracle database:
MERGE INTO %TABLE_NAME%_ATTRIBUTES x
USING (
SELECT PRIMARY_ID as SESSION_PRIMARY_ID, ? as ATTRIBUTE_NAME, ? as ATTRIBUTE_BYTES
FROM %TABLE_NAME%
WHERE SESSION_ID = ?
) y
ON (x.SESSION_PRIMARY_ID = y.SESSION_PRIMARY_ID and x.ATTRIBUTE_NAME=y.ATTRIBUTE_NAME)
WHEN MATCHED THEN
UPDATE SET x.ATTRIBUTE_BYTES = y.ATTRIBUTE_BYTES
WHEN NOT MATCHED THEN
INSERT(x.SESSION_PRIMARY_ID, x.ATTRIBUTE_NAME, x.ATTRIBUTE_BYTES) VALUES (y.SESSION_PRIMARY_ID, y.ATTRIBUTE_NAME, y.ATTRIBUTE_BYTES)
Perhaps Spring Session JDBC should use different session attribute queries by database?
There is precedent in Spring Session JDBC for database specific behavior such as 93aee206fbc20