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

时间:2015-01-06 22:28:30

标签: java spring hibernate

我知道这已经被问到了,但是我尝试了所有我找到的解决方案并且他们没有工作。 这里是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

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

弹簧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 个答案:

答案 0 :(得分:2)

一些观点:

  1. 您只需要在服务类方法或类顶部注释事务,以使所有方法都是事务性的。一般标准是注释方法。在DAO上注释@Transactional是不好的做法,应该避免使用。

  2. 尝试使用setter在您的DAO中设置DAO和DAO中的会话工厂,而不是依赖@Autowired版本可能是导致问题的根本原因。

    < / LI>
  3. 根本不需要你的AOP配置,Hibernate应该只是开箱即用。您可能会发现我写的here有用的问题。它为您提供了如何使用Spring 3设置Hibernate 4进行事务管理的指南。

  4. 祝你好运