Spring/Hibernate No session found for current thread (config) - spring

I'm trying to understand the configuration for Spring and Hibernate together. Every time I make calls to the database, I get a no session found for current thread error in my console (doesn't stop the app since I just create a new session if it can't find one). I have a standard STS Maven setup. The below is how I have the configuration currently setup. However, if I take everything in the root-context.xml and put it at the bottom of servlet-context.xml, it works without any errors. So I'm guessing something within servlet-context.xml is "overwriting" something and not taking the #Transactional annotations I have on my service. But how do you config around that?
root-context.xml
<!-- Configure JDBC Connection-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:C:\Users\Steven\Desktop\Programming\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin\bin\mydb" />
</bean>
<!-- Configure Hibernate 4 Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.css.genapp" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
servlet-context.xml
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- 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>
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basenames">
<beans:list>
<beans:value>format</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<context:component-scan base-package="com.css.genapp" />

You must define component scan on both servlet-context.xml and root-context.xml
root-context.xml: for service, repository...
servlet-context.xml: for controller and web relate component.
Hope it can help. You can check detail on this sample Spring, JPA and hibernate integration

I think in your Hibernate configuration you configured <prop key="hibernate.current_session_context_class">thread</prop> Like this.
Remove the property because it really breaks proper session/transaction management in spring.

You have to import root-context.xml since only servlet-context.xml will be read by dispatcher servlet. Add the following line in your servlet-context.xml :

Related

Transaction not getting committed

Working on a Spring 5 and Hibernate Project. Using Spring for bean management, transaction and MVC. The changes are not getting committed to database though i can see the insert statement in the log. There is no error. There is no issue with select statements. I could login into the application. Below are my configurations:
framework.xml:
<context:component-scan base-package="com.test" >
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource"
ref="dataSource"/>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="jtaTransactionManager" ref="transactionManager" />
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<property name="forceShutdown" value="false" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction">
<property name="transactionTimeout" value="300" />
</bean>
<!--
<bean id="HibernateTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
-->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" >
<property name="transactionManager"><ref bean="atomikosTransactionManager" /></property>
<property name="userTransaction"><ref bean="atomikosUserTransaction" /></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
In the above configuration, i excluded the controllers as they are loaded using a different mvc related config files.
The service classes were annotated with #Transactional.
I tried without JTA with plain HibernateTransactionManager also. The transactions are not getting committed.
The below entry is also for hibernate to use JTA as transaction manager
hibernate.transaction.jta.platform to org.hibernate.engine.transaction.jta.
platform.internal.AtomikosJtaPlatform and
hibernate.transaction.coordinator_class to jta
I am using getCurrentSession for getting hibernate session.
I have to use Atomikos as JTA transaction manager as the development has to be happen in servlet container.
Thanks in advance for any help to find the gap in the configuration or any other issues..
The problem was with the maven Jetty plugin and the db connection created didn't persist the changes with hibernate 5 with maven jetty plugin 9.4.35.v20201120 though it was working with hibernate 3 and maven jetty plugin 7.0.1.v20091125. When I deployed the same war file with pre-configured data source in tomcat, able to persist the changes.

Spring WebContentInterceptor is not adding cacheSeconds to header

I am trying to add configuration in spring mvc so that my static contents like js, images will be cached by browser. I have add the following in dispatcher-servlet.xml
<beans>
.............
<mvc:interceptors>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="31556926"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>
</beans>
But i still dont see the caching is enabled. I see the following in the browser debugger where it says Cache-Control:"no-cache".
Please help !!!
You can use mvc:resources for caching static files.
<mvc:resources mapping="/static/**" location="/public-resources/"
cache-period="31556926"/>
<mvc:annotation-driven/>
You're missing the cacheMappings property to configure path patterns / cache directives.
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="31556926"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
<property name="cacheMappings">
<props>
<prop key="/static/**">2592000</prop>
</props>
</property>
</bean>
But indeed, Burak Keceli's answer is spot on; you'd better use WebMvcConfigurerAdapter.addResourceHandlers or the XML configuration version with <mvc:resources/>.
I had the same problem. I added the interceptor but noting changed in the HTTP reponses.
In my case there was another spring context XML in my project where another <mvc:interceptors> was registered. It effectivly replaced my WebContentInterceptor configuration. Combining them solved it.
Perhaps something similar is going on in your configuration Abdus Samad...

Spring: JMSTemplate/CachingConnectionFactory deployables unable to start automatically in weblogic

I recently changed some of my application to use the the following:
org.springframework.jndi.JndiTemplate
org.springframework.jms.connection.CachingConnectionFactory
org.springframework.jms.core.JmsTemplate
Everything is working fine and I'm able to deploy my war files and send JMS messages to the queue.
However something peculiar happens when my managed server restarts. The deployables will all go into a fail state which requires me to then manually start them up.
This started happening after the change to use caching connection factory, jndi template and jms template.
My SpringConfig file:
<!-- Service Controller begin -->
<bean id="appUtils" class="com.foo.util.AppUtil" lazy-init="true" />
<bean id="jms_jndiTemplate" class="org.springframework.jndi.JndiTemplate" lazy-init="true">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">#{jmsJndiFactory}</prop>
<prop key="java.naming.provider.url">#{jmsIp}</prop>
</props>
</property>
</bean>
<bean id="jmsUtils" class="com.foo.JmsUtil" >
<property name="template">
<bean class="org.springframework.jms.core.JmsTemplate" lazy-init="true">
<property name="connectionFactory">
<bean class="org.springframework.jms.connection.CachingConnectionFactory" lazy-init="true">
<property name="sessionCacheSize" value="10" />
<property name="targetConnectionFactory">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jms_jndiTemplate" />
<property name="jndiName" ref="jmsFactory" />
</bean>
</property>
</bean>
</property>
</bean>
</property>
<property name="destination">
<bean class="org.springframework.jndi.JndiObjectFactoryBean" lazy-init="true">
<property name="jndiTemplate" ref="jms_jndiTemplate" />
<property name="jndiName" ref="jmsQueue" />
</bean>
</property>
</bean>
ApplicationContext file:
<bean id="jmsQueue" class="java.lang.String" ><constructor-arg value="${jmsQueue.local}" /></bean>
<bean id="jmsFactory" class="java.lang.String" ><constructor-arg value="${jmsFactory.local}" /></bean>
<bean id="jmsJndiFactory" class="java.lang.String" ><constructor-arg value="${jmsJndiFactory.local}" /></bean>
<bean id="jmsIp" class="java.lang.String" ><constructor-arg value="${jmsIp.local}" /></bean>
applicationProperties file:
jmsQueue.local=jms/Queue
jmsFactory.local=jms/ConnectionFactory
jmsJndiFactory.local=weblogic.jndi.WLInitialContextFactory
jmsIp.local=t3://localhost:7031
Anyone has any idea as to why this might be happening? I'm using Weblogic. Any help would be greatly appreciated.
Thanks!
Edit: Forgot to mention that the error causing the failed state is
javax.naming.NameNotFoundException: Unable to resolve 'jms.Queue'. Resolved 'jms'; remaining name 'Queue'.
This is a JNDI error. The message means "I tried to find jms/Queue in the JNDI context but I only got as far as jms; there is no Queue child below".
Check the resources which you configured for the application in WebSphere.

spring transaction and aop

I'm writing a simple application with spring, I defined my daos and services with spring annotations and defined hibernate as the orm and transaction manager like this:
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:env/hibernate.cfg.xml</value>
</property>
<property name="packagesToScan">
<list>
<value>com.skyfence.management.cm.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
like you can see I'm using annotations for the transactions management,
Until this point everything works fine.
Then I added a Logger Aspect to add log4j printouts before and after every method so I added the following to my applicationContext.xml
<aop:aspectj-autoproxy />
and created a new annotated aspect class:
#Aspect
#Component
public class LoggingAspect
{
}
The problem is that from that point hibernate is no longer working and I'm getting the following exception:
org.hibernate.HibernateException: No Session found for current thread
I suspect that somehow by adding the aspect the transactions stopped working but I have no idea how to solve it
Any help will be appreciated,

How to move location of Atomikos's tm.out and *.epoch files?

I'm running a J2SE application that uses Atomikos which dumps it's numerous log files to the current directory. I'd like to move the location of these files to "/tmp", but I cannot locate a configuration property that I can set from within my Spring XML config file.
The Atomikos documentation references a property:
com.atomikos.icatch.output_dir
Which seems exactly what I need, but how to set from Spring it without a jta.properties file? Here is my transaction manager config:
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="atomikosTransactionManager" />
<property name="userTransaction" ref="atomikosUserTransaction" />
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<!-- When close is called, should we force transactions to terminate? -->
<property name="forceShutdown" value="false" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<!-- Number of seconds before transaction timesout. -->
<property name="transactionTimeout" value="30" />
</bean>
The property in question must be set on the singleton instance of the transactionService -- an object that is normally created on-demand by the user transaction manager:
<bean id="userTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp"
init-method="init" destroy-method="shutdownForce">
<constructor-arg>
<!-- IMPORTANT: specify all Atomikos properties here -->
<props>
<prop key="com.atomikos.icatch.service">com.atomikos.icatch.standalone.UserTransactionServiceFactory</prop>
<prop key="com.atomikos.icatch.output_dir">target/</prop>
<prop key="com.atomikos.icatch.log_base_dir">target/</prop>
</props>
</constructor-arg>
</bean>
Now the property is set. But in order to ensure you don't have two transaction services running you must also modify the user transaction manager bean as follows:
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close" depends-on="userTransactionService">
<!-- When close is called, should we force transactions to terminate? -->
<property name="forceShutdown" value="false" />
<!-- Do not create a transaction service as we have specified the bean in this file -->
<property name="startupTransactionService" value="false" />
</bean>

Resources