Spring+Hibernate: No session found in the thread - spring-mvc

I have made a project which is built on Maven+Spring 3.1+Spring MVC 3.1+Hibernate 4.1
In the transaction if I use the code:
Session session=sessionFactory.getCurrentSession();
session.save(user);
It gives the exception at the getCurrentSession():
SEVERE: Servlet.service() for servlet appServlet threw exception
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.company.cv.dao.UserDAO.saveUser(UserDAO.java:30)
at com.company.cv.service.UserService.saveUser(UserService.java:20)
at com.company.cv.HomeController.saveUser(HomeController.java:44)
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.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
But if I use openSession instead of getCurrentSession no exceptions and code transaction completes successfully:
Session session = sessionFactory.openSession();
session.save(user);
What is the reason?
Thanks for the help
My applicationContext.xml:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/companycv" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.company.cv.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
servlet-context.xml:
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.company.cv" />
My service code:
#Service
public class UserService implements UserServiceIntf{
#Autowired
UserDAOIntf userDAO;
#Transactional
public void saveUser(User user) {
userDAO.saveUser(user);
}
}
My DAO code:
#Repository
public class UserDAO implements UserDAOIntf {
#Autowired
SessionFactory sessionFactory;
public void saveUser(User user) {
Session session=sessionFactory.getCurrentSession();
session.save(user);
}
}

You need add #Transactional annotation above your service method calling DAO method save. And since you have txManager defined in your app context you need not to manually manage the transactions.

One thing that I have observed you are doing wrong is that you are mixing the usage of Hibernate transaction API with the Spring managed transactions management abstraction. This is strictly not advised.
Session session=sessionFactory.getCurrentSession();
Transaction tx=session.beginTransaction(); // This is using Hibernate transaction API
session.save(user);
sessionFactory.getCurrentSession().save(user);
tx.commit();// This is using Hibernate transaction API
In the above code you are using hibernate transaction api to manage the transaction along with the Spring transaction management (when you annotate your Service method with transactional annotation)
You need to only use this
Session session=sessionFactory.getCurrentSession();
session.save(user);
sessionFactory.getCurrentSession().save(user);
Also as pointed out by others you have got duplicate datasource definitions listed.
And you mention that you can’t get sessionFactory which does not make sense as it is injected via Spring and you say that in the other case you have access to sessionFactory. There is no reason why this should happen.
UPDATE
So you are saying that you do have sessionFactory accessible in both cases but it’s not working in case of getCurrentSession. Having made all the changes suggested, the best advise will be to see what’s happening under the hood by enabling the Hibernate logging and Spring framework logging in log4j configuration ( if you are using log4j) track the relevant activity.
Your log4j configuration file would be something like this
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=<file-path>
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger
log4j.rootLogger=INFO, file
# Hibernate and Spring logging
log4j.logger.org.hibernate=DEBUG
log4j.logger.org.springframework.transaction=DEBUG
This would give you a clear picture.

It was because of Hibernate4. If you look at the Hibernate4 DOC like I should have done in the first place ( :D ) Hibernate4 you have openSession every time. I think Hibernate guys made it so that noobies like me will be forced to use new session every time. Because session is not thread safe. FYI Hibernate openSession() vs getCurrentSession()

Related

Spring 5 MVC Test with MockMvc, test-context.xml, and annotation-based WebAppConfig (ie, in Java)

Versions (SpringBoot is not involved):
Spring: 5.2.16
web-app / servlet API: 4.0
JUnit: 5.8
Spring MVC Testing is not working for controller endpoint that returns ResponseEntity<ReturnStatus>, where ReturnStatus is a POJO with appropriate getters/setters. The exception triggered indicates that JSON conversion is not working for ReturnStatus. My research indicates that the annotation-based Java configuration for the WebApplicationContext is not loaded (and therefore the Jackson JSON converter is not recognized). Curiously, in a non-testing deployment in Tomcat, the controller endpoint works fine, presumably because the web.xml in the war-file is parsed by Tomcat.
QUESTION:
How can I adjust the setup for Spring MVC Test for this application so that the annotation-based Java configuration for the WebApplicationContext is properly loaded? Can this, for example, be done explicitly in the endpoint-test logic (ie, the JUnit test)?
Exception:
14:33:57,765 WARN DefaultHandlerExceptionResolver:199 - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.acme.myapp.io.ReturnStatus] with preset Content-Type 'null']
14:33:57,765 DEBUG TestDispatcherServlet:1131 - Completed 500 INTERNAL_SERVER_ERROR
The Spring MVC app incorporates the following configurations:
test-context.xml, which houses Spring bean-configuration for access to data store:
web.xml, which declares and maps the DispatcherServlet with relevant setup for WebApplicationContext.
Annotation-based configuration in Java implementation of WebMvcConfigurer.
Relevant excerpt from test-context.xml:
<context:component-scan base-package="com.acme.myapp"/>
<jpa:repositories base-package="com.acme.myapp.repos"/>
<context:property-placeholder location="classpath:/application.properties" />
<!-- Data persistence configuration -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.showSql}" />
<property name="databasePlatform" value="${db.dialect}" />
<property name="generateDdl" value="${db.generateDdl}" />
</bean>
</property>
<property name="packagesToScan">
<list>
<value>com.acme.myapp.dao</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.pass}" />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
<property name="accessToUnderlyingConnectionAllowed" value="true"/>
</bean>
<!-- Set JVM system properties here. We do this principally for hibernate logging. -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
</property>
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="org.jboss.logging.provider">slf4j</prop>
</util:properties>
</property>
</bean>
Relevant excerpt from web.xml (where application-context.xml is our production version of test-context.xml):
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>central-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.acme.myapp.MyAppWebAppConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>central-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
Excerpt from Java implementation of WebMvcConfigurer (ie, where we incorporate Jackson JSON converter):
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.acme.myapp.controllers" })
public class MyAppWebAppConfig implements WebMvcConfigurer
{
private static final Logger logger = LoggerFactory.getLogger(MyAppWebAppConfig.class);
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters)
{
logger.debug("extendMessageConverters ...");
converters.add(new StringHttpMessageConverter());
converters.add(new MappingJackson2HttpMessageConverter(new MyAppObjectMapper()));
}
}
The controller endpoint looks like this (where the root is at /patients):
#RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ReturnStatus> readPatient(
#PathVariable("id") long id
)
{
ReturnStatus returnStatus = new ReturnStatus();
returnStatus.setVersionId("1.0");
...
return new ResponseEntity<ReturnStatus>(returnStatus, httpStatus);
}
Using JUnit5 and MockMvc, the endpoint-test looks like this:
#SpringJUnitWebConfig(locations={"classpath:test-context.xml"})
public class PatientControllerTest
{
private MockMvc mockMvc;
#BeforeEach
public void setup(WebApplicationContext wac) {
this.mockMvc = webAppContextSetup(wac).build();
}
#Test
#DisplayName("Read Patient from /patients API.")
public void testReadPatient()
{
try {
mockMvc.perform(get("/patients/1").accept(MediaType.APPLICATION_JSON_VALUE))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Thanks!
Here are some options, possibly not exhaustive:
Per earlier comment, we can simply use <mvc:annotation-driven> directive in test-context.xml. For example:
<bean id="myappObjectMapper" class="com.acme.myapp.MyAppObjectMapper"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<constructor-arg ref="myappObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Effectively, this directive obviates the need for loading MyAppWebAppConfig, as <mvc:annotation-driven> in fact is the XML-equivalent of the annotation #EnableWebMvc in Java.
Implement WebApplicationInitializer so that effectively does in Java what we configure into web.xml. For example:
public class MyAppWebApplicationInitializer implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext container)
{
XmlWebApplicationContext appCtx = new XmlWebApplicationContext();
appCtx.setConfigLocation("classpath:application-context.xml");
container.addListener(new ContextLoaderListener(appCtx));
AnnotationConfigWebApplicationContext dispatcherCtx = new AnnotationConfigWebApplicationContext();
dispatcherCtx.register(MyAppWebAppConfig.class);
ServletRegistration.Dynamic registration = container.addServlet("central-dispatcher", new DispatcherServlet(dispatcherCtx));
registration.setLoadOnStartup(1);
registration.addMapping("/api/*");
}
}
For this solution, we expunge web.xml from the project; possibly we should parameterize the reference to application-context.xml as well.
Note that when I run JUnit5 tests, it appears that Spring does not instance MyAppWebApplicationInitializer, and that instead, the Spring context loaded for JUnit5 is the one referenced by the #SpringJUnitWebConfig annotation. I therefore recommend co-locating test-related configuration with test-context.xml, and reserving WebApplicationInitializer for production.
I'm sure there are other options, but I've only explored these two approaches.

Error TIMEOUT WAITING FOR ACK - RabbitMq Publiser Confirms Async Implementation

We have implemented publisher confirms asynchronously i.e. we have setup callbacks on RabbitTemplates to get response from RabbitMq; but we are getting below exception in the logs:-
{"ts":"02 24 2021 14:33:21.308","th":"connectionFactory4002","tenant":"","user":"null","trxid":"","level":"DEBUG","logger":"org.springframework.amqp.rabbit.connection.PublisherCallbackChannelImpl","msg":Sending confirm PendingConfirm [correlationData=CorrelationData [id=7d329ab2-2472-4222-91d0-9bc68dc405c7] cause=clean channel shutdown; protocol method: #method<channel.close>(reply-code=406, reply-text=TIMEOUT WAITING FOR ACK, class-id=0, method-id=0)] }
"ERROR","logger":"com.rabbitmq.client.impl.ChannelN","msg":{​​​​​[com.rabbitmq.client.impl.ChannelN.waitForConfirmsOrDie(ChannelN.java:254),org.springframework.amqp.rabbit.connection.PublisherCallbackChannelImpl.waitForConfirmsOrDie(PublisherCallbackChannelImpl.java:676),org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.lambda$asyncClose$1(CachingConnectionFactory.java:1371),java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142),java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617),java.lang.Thread.run(Thread.java:745)]}​​​​​ ,"ERR": {​​​​​ java.util.concurrent.TimeoutException
at com.rabbitmq.client.impl.ChannelN.waitForConfirms(ChannelN.java:223)
at com.rabbitmq.client.impl.ChannelN.waitForConfirmsOrDie(ChannelN.java:249)
at org.springframework.amqp.rabbit.connection.PublisherCallbackChannelImpl.waitForConfirmsOrDie(PublisherCallbackChannelImpl.java:676)
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.lambda$asyncClose$1(CachingConnectionFactory.java:1371)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
--Connection Factory Config
<bean id="connectionFactory"
class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<constructor-arg value="#{messagingProperties['mq.hostname']}" />
<property name="virtualHost" value="#{messagingProperties['mq.virtual-host']}" />
<property name="username" value="#{messagingProperties['mq.username']}" />
<property name="password" value="#{messagingProperties['mq.password']}" />
<property name="connectionTimeout" value="10000"/>
<property name="channelRpcTimeout" value="60000"/>
<property name="channelCacheSize" value="25" />
</bean>
We have following queries regarding this :
How to prevent this error/log?
Is there message loss due to the above error?
Apart from resource utilization, is there any side impact of this error?
Do the confirmCallBack/returnCallBack call this method(waitForConfirmsOrDie) behind the scenes?

Invalidated object not currently part of this pool

When I use redisCacheManager to put something, it throws an exception "Invalidated object not currently part of this pool". But when I set the usePool to false, it can work. I think this is a Multi-threaded case. But I don't know why the spring-data-redis's annotation can work.
<code>
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext.xml");
UserServiceImpl userService = applicationContext.getBean(UserServiceImpl.class);
RedisCacheManager redisCacheManager = applicationContext.getBean(RedisCacheManager.class);
redisCacheManager.getCache("cacheName").put("key","value");
<cache:annotation-driven ></cache:annotation-driven>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory"/>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"></property>
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
</bean>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:template-ref="redisTemplate"/>
</code>

Spring Integration Proxy Settings using HttpCllient

I am using spring integration 4.1.2 (ws and core) trying to use HTTPClient (apache) on transport.
I thought that following some reading and configuring the messageSender and messageFactory Spring would use the settings configured on XML (application context) but the configuration is not working as expected.
My xml to configure the HttpClient follows:
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig" factory-method="custom">
<property name="socketTimeout" value="${saog.connection.timeout}" />
<property name="connectTimeout" value="${saog.connection.timeout}" />
</bean>
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
<bean id="httpHostProxy" class="org.apache.http.HttpHost">
<constructor-arg index="0" value="10.1.6.91" ></constructor-arg>
<constructor-arg index="1" value="80"></constructor-arg>
</bean>
<!-- <property name="defaultHeaders" ref="defaultHeaders"></property> -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="defaultRequestConfig" ref="requestConfig" />
<property name="proxy" ref="httpHostProxy"></property>
</bean>
<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build" />
<bean id="httpComponentsClientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
</bean>
<bean id="defaultMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender" ref="defaultMessageSender" />
</bean>
From here using the ws:outbound-gateway i am facing some problems with configuration:
I made a service with the following parameter as configuration:
<ws:outbound-gateway
uri="${server.address}/${endpoint}"
interceptor="anintercerptor"
message-factory="messageFactory" message-sender="defaultMessageSender">
<ws:request-handler-advice-chain>
<ref bean="retryAdvice" />
</ws:request-handler-advice-chain>
</ws:outbound-gateway>
But when I'm debugging the proxy is not being set (but the timeout it is and the timeout is in the same bean config). and the ApplicationServer is throwing an exception and by my surprise the transport (http) is the JavaNative transport.
A sample of the error follow bellow:
java.io.IOException:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:412)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:271)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:258)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:376)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:437)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:551)
at com.ibm.net.ssl.www2.protocol.https.c.<init>(c.java:143)
at com.ibm.net.ssl.www2.protocol.https.c.a(c.java:67)
at com.ibm.net.ssl.www2.protocol.https.d.getNewHttpClient(d.java:55)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:935)
at com.ibm.net.ssl.www2.protocol.https.d.connect(d.java:10)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1043)
at com.ibm.net.ssl.www2.protocol.https.b.getOutputStream(b.java:62)
at org.springframework.ws.transport.http.HttpUrlConnection.getRequestOutputStream(HttpUrlConnection.java:85)
at org.springframework.ws.transport.AbstractSenderConnection$RequestTransportOutputStream.createOutputStream(AbstractSenderConnection.java:106)
at org.springframework.ws.transport.TransportOutputStream.getOutputStream(TransportOutputStream.java:41)
at org.springframework.ws.transport.TransportOutputStream.write(TransportOutputStream.java:64)
at com.ibm.ws.webservices.utils.LowFlushFilter.write(LowFlushFilter.java:70)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:355)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(StreamEncoder.java:425)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(StreamEncoder.java:429)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:175)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:274)
at com.ibm.ws.webservices.utils.BufferedWriter.flush(BufferedWriter.java:318)
at com.ibm.ws.webservices.engine.SOAPPart.writeTo(SOAPPart.java:841)
at com.ibm.ws.webservices.engine.Message.writeTo(Message.java:669)
at org.springframework.ws.soap.saaj.SaajSoapMessage.writeTo(SaajSoapMessage.java:275)
at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:46)
at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:654)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:603)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
at org.springframework.integration.ws.SimpleWebServiceOutboundGateway.doHandle(SimpleWebServiceOutboundGateway.java:93)
at org.springframework.integration.ws.AbstractWebServiceOutboundGateway.handleRequestMessage(AbstractWebServiceOutboundGateway.java:188)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler$AdvisedRequestHandler.handleRequestMessa
And clue how to solve the Proxy config setting using the HttpClient on SpringIntegration?
Regards.
Jose Carlos Canova.

OpenSessionInView working but not providing its session for #Transactional

I am trying to use Spring MVC 3 and Hibernate 4.1 to get declarative transaction management, providing an open session for the entire length of the request. I only have one "manager" layer for data access, which directly uses the session. This is annotated with #Transactional, and the session closes upon exiting this layer and I get a lazy load exception in the controller.
So I added the OpenSessionInViewFilter filter, and the logs state that this filter is correctly configured and they also show this filter opening a session. Unfortunately, my manager layer opens and closes its own session anyway, just as before, and I get the same lazy load exception in the controller.
Edit: noted that in my log, I get the filter session open, HibernateTransactionManager session open, HibernateTransactionManager session closed, lazy load exception, then filter session closed. So I know that there is an open session somewhere during the lazy load exception, but the object was loaded in a transaction associated with the other, closed session.
I thought that removing #Transactional from the manager class would remove session management from that layer and let the filter do its job, but then the sessionFactory().getCurrentSession() simply gets a closed session; it doesn't have access to the filter's provided open session.
How can I get access to the OpenSessionInViewFilter's clearly open session?
springapp-servlet.xml
<beans ..
<context:component-scan base-package="springapp.web" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="userManager" class="springapp.service.SimpleUserManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<import resource="hibernate-context.xml" />
</beans>
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springapp-servlet.xml</param-value>
</context-param>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
hibernate-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ..
">
<context:property-placeholder location="/WEB-INF/hibernate.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven />
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean id="managerTemplate" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="databeans" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
</beans>
manager.java
#Service("userManager")
#Transactional
public class SimpleUserManager implements UserManager {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
..
controller.java
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
private UserManager userManager;
..
and my exception, which occurs in the controller, on the first property read of an object loaded in the manager class and passed to that controller:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:119)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
I've been researching this for hours.. all I can find is a mix of solutions using hibernate 3 and grainy explanations on hibernate 4 session/transaction theory without examples.
Any thoughts?
UPDATE: FIXED!
Found this:
Spring MVC OpenSessionInViewInterceptor Not Working
which unfortunately has not helped the OP there, but it helped me. Notably, this:
"it will be better to not import applicationContext.xml in dispatcher-servlet.xml, instead load it using a ContextLoaderListener"
which, applied to my configuration, is exactly everything I have posted above, but instead of
<import resource="hibernate-context.xml" />
in my springapp-servlet.xml, I modified my ContextLoaderListener to:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springapp-servlet.xml, /WEB-INF/hibernate-context.xml</param-value>
</context-param>
and that was all it took for
sessionFactory.getCurrentSession()
to return to me the OSIV-created session. And, in fact, the second session that was being created is no longer, as I found these lovely little log lines:
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
2012-10-04 14:43:48,743 TRACE http-8080-1 org.springframework.transaction.support.TransactionSynchronizationManager - Retrieved value [org.springframework.orm.hibernate4.SessionHolder#4146c5c0] for key [org.hibernate.internal.SessionFactoryImpl#12542011] bound to thread [http-8080-1]
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.orm.hibernate4.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.orm.hibernate4.HibernateTransactionManager - Creating new transaction with name [springapp.service.SimpleUserManager.find]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
which show that, outside of my #Transactional service layer, the OSIV-created session was alive and well, and a new transaction was simply started for it.
Hope this helps someone else. I don't even want to think about how many hours I spent working on it.

Resources