Andreu Andreu - 7 months ago 12
Java Question

Spring Transaction Hibernate @Transaction annotation not working with @Autowired

Spring Transaction Hibernate

@Transaction
annotation is not working with
@Autowired
correctly. If I create the
Dao`` element by
xml(UserDao2 userDao2)`,

the transactional anotation in the Service class is working, if its by
@Repository
annotation in the Dao class when tries to getCurrentSesion, says:

org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) ~[spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE]
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:993) ~[hibernate-core-4.2.11.Final.jar:4.2.11.Final]


It appears that is not linking well the
@Transactional
annotation with the session factory

Library versions:

<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<hibernate.version>4.2.11.Final</hibernate.version>


spring-database.xml

<context:annotation-config />

<jee:jndi-lookup id="datasourcenn" jndi-name="java:/comp/env/nn_datasource" />

<bean id="sesionHibernate"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource" ref="datasourcenn"/>

<property name="packagesToScan" value="com.web.entity"/>

<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</prop>




<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop>

<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>

<!-- nuevas properties de configuraciĆ³n -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">50</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>

<prop key="hibernate.bytecode.provider">cglib</prop>


</props>
</property>
</bean>


<bean id="us" class="com.web.dao.UserDaoImpl">
<property name="sesionHibernate" ref="sesionHibernate" />
</bean>
<!-- -->
<bean id="userDao2" class="com.web.dao.UserDao2Impl">
<property name="sesionHibernate" ref="sesionHibernate" />
</bean>



<bean id="myUserDetailsService" class="com.web.service.UsuarioServiceImpl">
<property name="userDao" ref="us" />
</bean>
<!--
proxy-target-class="true" mode="aspectj"
-->

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

</bean>

<tx:annotation-driven transaction-manager="transactionManager" />


UserDao2 (I remove @Repository if I create it by xml)

@Repository
public class UserDao2Impl implements UserDao2 {
private static Logger log = LoggerFactory.getLogger(UserDao2Impl.class);

@Autowired
@Qualifier("sesionHibernate")
private SessionFactory sesionHibernate;

@SuppressWarnings("unchecked")
public Usuario findByUserName(String username) {
try {
log.info("findByUserName" + sesionHibernate);

List<Usuario> users = new ArrayList<Usuario>();
System.out.println(sesionHibernate+"\n----------");

users = sesionHibernate.getCurrentSession().createQuery("from Usuario where nombre=?").setParameter(0, username).list();
// users = sesionHibernate.getCurrentSession().createQuery("from Usuario
// where nombre=?").setParameter(0, username).list();

if (users.size() > 0) {
return users.get(0);
} else {
return null;
}

} catch (Exception e) {
log.error("findByUserName ", e);
return null;
}
}


Usuario2ServiceImpl If have the service with @Transacional

@Service
@Transactional
public class Usuario2ServiceImpl implements Usuario2Service {
private static Logger log = LoggerFactory.getLogger(Usuario2ServiceImpl.class);

//Qualifier("userDaoImpl")
@Autowired
private UserDao2 userDao2;



@Override
public com.web.entity.Usuario getUsuariodetalles(final String nombreUsuario) throws UsernameNotFoundException {
log.info("getUsuariodetalles - 1");
System.out.println("ssss"+userDao2);
com.web.entity.Usuario usuario = userDao2.findByUserName(nombreUsuario);


log.info("getUsuariodetalles - 2");
return usuario;

}

Answer

Solution, i add to mvc-dispatcher-servlet.xml, mvc:interceptors configuration to open session with org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor. Just need to define the sessionFactory in the properties.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd    
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        ">
    <context:annotation-config />
    <context:component-scan base-package="com.web" />

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean name="OpenSessionInViewInterceptorCom" class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
                <property name="sessionFactory">
                    <ref bean ="sesionHibernate" />
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- Configures the @Controller programming model -->

    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/img/**" location="/img/" />
    <mvc:resources mapping="/js/**" location="/js/" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>



</beans>
Comments