Estado HTTP 500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:没有活动事务,createQuery无效

时间:2014-07-09 22:55:51

标签: java spring hibernate

任何人都可以解释这个错误吗?我进入了这行代码。 列表empresas = session.createQuery(“来自Empresas”)。list(); of EmpresasDAOImp.java

jul 10, 2014 1:17:32 AM org.apache.catalina.core.StandardWrapperValve invoke
Grave: El Servlet.service() para el servlet [springapp] en el contexto con ruta [/springapp] lanzó la excepción [Request processing failed; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction] con causa raíz
org.hibernate.HibernateException: createQuery is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
    at com.sun.proxy.$Proxy19.createQuery(Unknown Source)
    at com.altobri.conta.dao.EmpresasDAOImpl.listEmpresas(EmpresasDAOImpl.java:50)
    at com.altobri.conta.service.EmpresasServiceImpl.listEmpresas(EmpresasServiceImpl.java:48)
    at com.altobri.conta.controller.empresaListaController.list(empresaListaController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

的web.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <display-name>Spring3MVC</display-name>
 <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
 <servlet-name>springapp</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

springapp-servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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">

   <context:component-scan base-package="com.companyname.springapp.web" />
   <context:component-scan base-package="com.springHibernate" />
   <context:component-scan base-package="com.altobri.conta.*" />

 <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>


     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/empresas" />
    <property name="username" value="root" />
    <property name="password" value="" />
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
     <property name="annotatedClasses">
            <list>
                <value>com.altobri.conta.model.Empresas</value>
            </list>
        </property>
    <property name="hibernateProperties">
      <props>
        <prop 
         key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.current_session_context_class">thread</prop>
      </props>
    </property>
  </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" 
    p:sessionFactory-ref="sessionFactory">
  </bean>
</beans>

empresaListaController.java

package com.altobri.conta.controller;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import com.altobri.conta.model.Empresas;
import com.altobri.conta.service.*;

@Controller
public class empresaListaController {

    @Autowired
    private EmpresasService empresasService;
    protected final Logger logger = Logger.getLogger(getClass());


    @RequestMapping("/empresaLista")
    // @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {

      List<Empresas> empresas = empresasService.listEmpresas();
      model.addAttribute("empresalist", empresas);
      return "empresaLista";
    }
}

EmpresasDAO

package com.altobri.conta.dao;

import com.altobri.conta.model.Empresas;
import java.util.List;

public interface EmpresasDAO {
    void persistEmpresas(Empresas empresas);

    Empresas findEmpresasById(int clave);

    void updateEmpresas(Empresas empresas);

    void deleteEmpresas(Empresas empresas);

    public List<Empresas> listEmpresas();

}

EmpresasDAOImpl.java

    package com.altobri.conta.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.altobri.conta.model.Empresas;

@Repository("empresasDAO")
public class EmpresasDAOImpl implements EmpresasDAO {

    @Autowired
    public SessionFactory sessionFactory;

    @Override
    @Transactional
    public void persistEmpresas(Empresas empresas) {
        sessionFactory.getCurrentSession().persist(empresas);
    }

    @Override
    @Transactional
    public Empresas findEmpresasById(int clave) {
        return (Empresas) sessionFactory.getCurrentSession().get(
                Empresas.class, clave);
    }

    @Override
    @Transactional
    public void updateEmpresas(Empresas empresas) {
        sessionFactory.getCurrentSession().update(empresas);

    }

    @Override
    @Transactional
    public void deleteEmpresas(Empresas empresas) {
        sessionFactory.getCurrentSession().delete(empresas);

    }

    @Override
    @Transactional
    public List<Empresas> listEmpresas() {
        Session session = sessionFactory.getCurrentSession();
        List empresas = session.createQuery("from Empresas").list();
        // TODO Auto-generated method stub
         return empresas;
    }

}

Empresas.java

package com.altobri.conta.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EMPRESAS")
public class Empresas {

    @Id
    @Column(name = "CLAVE", nullable = false)
    private int clave;

    @Column(name = "NOMBRE", nullable = false)
    private String nombre;


    public Empresas() {


    }


    public int getClave() {
        return clave;
    }


    public void setClave(int clave) {
        this.clave = clave;
    }


    public String getNombre() {
        return nombre;
    }


    public void setNombre(String nombre) {
        this.nombre = nombre;
    }



}

EmpresasService.java

package com.altobri.conta.service;



import java.util.List;

import com.altobri.conta.model.Empresas;

public interface EmpresasService {

    void persistEmpresas(Empresas empresas);

    Empresas findEmpresasById(int clave);

    void updateEmpresas(Empresas empresas);

    void deleteEmpresas(Empresas empresas);

    public List<Empresas> listEmpresas();
}

EmpresasServiceImpl.java

    package com.altobri.conta.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.altobri.conta.dao.EmpresasDAO;
import com.altobri.conta.model.Empresas;

@Service("empresasService")
public class EmpresasServiceImpl implements EmpresasService{

    @Autowired
    EmpresasDAO empresasDAO;

    @Override
    @Transactional
    public void persistEmpresas(Empresas empresas) {
        empresasDAO.persistEmpresas(empresas);

    }

    @Override
    @Transactional
    public void updateEmpresas(Empresas empresas) {
        empresasDAO.updateEmpresas(empresas);

    }
    @Override
    @Transactional
    public Empresas findEmpresasById(int clave) {
        return empresasDAO.findEmpresasById(clave);
    }

    @Override
    @Transactional
    public void deleteEmpresas(Empresas empresas) {
        empresasDAO.deleteEmpresas(empresas);

    }

    @Override
    @Transactional
    public List<Empresas> listEmpresas() {
        // TODO Auto-generated method stub
        return empresasDAO.listEmpresas();
    }

}

1 个答案:

答案 0 :(得分:1)

@Override
public List<Empresas> listEmpresas() {
    // TODO Auto-generated method stub
    return empresasDAO.listEmpresas();
}

未使用@Transactional进行注释。在该方法堆栈中,您尝试调用一个要求您进入事务的方法。

@Override
public List<Empresas> listEmpresas() {
    Session session = sessionFactory.getCurrentSession();
    List empresas = session.createQuery("from Empresas").list(); // needs to be called within a Transaction
     return empresas;
}

此外,您缺少交易注释配置

<tx:annotation-driven />

(不要忘记添加适当的tx命名空间声明。)