当前线程的事务同步会话 Hibernate4 异常 spring 4

transaction-synchronized Session for current thread Hibernate4 Exception spring 4

我知道有人问过这个问题,但我尝试了我找到的所有解决方案,但都没有用。 这里是堆栈跟踪:

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[=1=]0(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.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.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

这是我的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
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
@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;
}}

如有任何帮助,我们将不胜感激

点数:

  1. 您只需在您的服务 class 方法上或 class 的顶部注释事务性,即可使所有方法成为事务性的。一般标准是注释方法。在您的 DAO 上注释 @Transactional 是不好的做法,应该避免。

  2. 尝试在您的服务 class 中设置您的 DAO 并使用 setter 在您的 DAO 中设置您的会话工厂并且不依赖于 @Autowired 版本可能是问题的根本原因。

  3. 根本不需要您的 AOP 配置,Hibernate 应该开箱即用。我写的 here 问题可能会对您有所帮助。它为您提供了有关如何使用 Spring 3 设置 Hibernate 4 以进行事务管理的指南。

祝你好运