2

i know there this is already asked, but i tried with all the solutions i found and they didn´t work. here is the stacktrace:

15:47:22,750 ERROR [io.undertow.request] (default task-21) UT005023: Exception handling request to /usuarios/user/: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_25]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_25]
Caused by: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) [spring-orm-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at com.esprbca.usuarios.dao.impl.UsuarioDaoImpl.listUsuarios(UsuarioDaoImpl.java:56) [classes:]
at com.esprbca.usuarios.service.impl.UsuarioServiceImpl.listUsuarios(UsuarioServiceImpl.java:42) [classes:]
at com.esprbca.usuarios.controller.UsuariosController.paginaUsuarios(UsuariosController.java:64) [classes:]
at com.esprbca.usuarios.controller.UsuariosController.GET(UsuariosController.java:35) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_25]
at java.lang.reflect.Method.invoke(Method.java:483) [rt.jar:1.8.0_25]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) [spring-web-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.3.RELEASE.jar:4.1.3.RELEASE]
... 30 more

this is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-hibernate.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

servlet-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- 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="/static/**" location="/static/" />

<!-- 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.esprbca.usuarios.controller,com.esprbca.usuarios.service,com.esprbca.usuarios.dao" />

</beans:beans>

spring-hibernate.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
        </list>
    </property>
</bean>

<bean id="escaDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="${jdniName}" />
</bean>

<!-- hibernate session -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="escaDataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
        </props>
    </property>

    <!-- autoscan annotation for hiberante config -->
    <property name="packagesToScan">
        <list>
            <value>com.esprbca.usuarios.entities</value>
        </list>
    </property>
</bean>

<!-- transaction manager -->
<bean name="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- the transactional advice (what happens; see the <aop:advisor/> bean below) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- the transactional semantics... -->
    <tx:attributes>
        <!-- all methods starting with get are read-only -->
        <tx:method name="retrieve*" read-only="true"/>
        <!-- other methods use the default transaction settings (see below) -->
        <tx:method name=""/>
    </tx:attributes>
</tx:advice>

<!-- ensure that the above transactional advice runs for any execution
    of an operation defined by the serviceUpdateOperations -->
<aop:config>
    <aop:pointcut id="serviceUpdateOperations"
                  expression="execution(* com.esprbca.usuarios.service.impl.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceUpdateOperations"/>
</aop:config>
</beans>

Controller:

@Controller
public class UsuariosController /* implements Controller */ {

protected final Log logger = LogFactory.getLog(getClass());

@Autowired
private UsuarioServiceI usuarioService;


@RequestMapping(value="/user")
public ModelAndView GET(HttpServletRequest request, HttpServletResponse response){
    logger.error("passed controller");
    return paginaUsuarios();
}
public ModelAndView paginaUsuarios(){
    Collection<Usuario> usuariosList = usuarioService.listUsuarios();
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("usuarios", usuariosList);
    ModelAndView mv = new ModelAndView("usuarios", "model", model);
    return mv;
}}

Service:

@Service
@Transactional
public class UsuarioServiceImpl implements UsuarioServiceI{

@Autowired
private UsuarioDaoI usuarioDAO;

public void setUsuarioDAO(UsuarioDaoI usuarioDAO) {
    this.usuarioDAO = usuarioDAO;
}

@Override
@Transactional
public void addUsuario(String usuario, String passwd, String nombres,
        String apellidos, String email, String telefono, int perfilid,
        boolean activo) {
    this.usuarioDAO.addUsuario(usuario, passwd, nombres, 
            apellidos, email, telefono, perfilid, activo);
}

@Override
@Transactional
public void updateUsuario(Usuario u) {
    this.updateUsuario(u);
}

@Override
@Transactional
public List<Usuario> listUsuarios() {
    return this.usuarioDAO.listUsuarios();
}

@Override
@Transactional
public Usuario getUsuarioById(String usuario) {
    return this.usuarioDAO.getUsuarioById(usuario);
}

@Override
@Transactional
public List<Usuario> getUsuariosLike(String pattern) {
    return this.usuarioDAO.getUsuariosLike(pattern);
}}

DAO:

@Repository
@Transactional
public class UsuarioDaoImpl implements UsuarioDaoI{

private static final Logger logger = LoggerFactory.getLogger(UsuarioDaoImpl.class);

@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf){
    this.sessionFactory = sf;
}

@SuppressWarnings("unchecked")
@Transactional
public List<Usuario> listUsuarios() {
    List<Usuario> usuarioList = (List<Usuario>) sessionFactory.
                getCurrentSession().createCriteria(Usuario.class).list();
    return usuarioList;
}}

any help would be appreciated

2
  • 1
    Your transaction configuration is loaded by the ContextLoaderListener while your services are loaded by the DispatcherServlet, that isn't going to work. AOP only works in the same context it it defined in.
    – M. Deinum
    Commented Jan 7, 2015 at 6:42
  • than you, you helped me a lot, one of the problems is that in the servlet context i scanned all the anotated classes, the solution: scan only the anotated controllers in the servlet context, and the dao and services implementations in the hibernate context
    – lennin92
    Commented Jan 8, 2015 at 18:06

1 Answer 1

3

A number of points:

  1. You only need to annotate transactional on your service class methods or at the top of the class, to make all methods transactional. The general standard is to annotate the methods. Annotating @Transactional on your DAO, is bad practice and should be avoided.

  2. Trying to set your DAO in your service class and your session factory in your DAO using a setter and not relying on the @Autowired version is probably the root cause of your problem.

  3. Your AOP config shouldn't be needed at all, Hibernate should just work out of the box. You may find a question that I've written here to be helpful. It gives you a guide on how to setup Hibernate 4 with Spring 3 for transaction management.

Best of luck

1
  • thank your very much, in fact, one of the problems was that I tried to use the set the dao on the service class and the session in the dao class instead of using the @autowired.
    – lennin92
    Commented Jan 8, 2015 at 18:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.