“org.hibernate.TransactionException:不支持嵌套事务”但我没有嵌套事务

时间:2016-03-15 02:11:45

标签: java spring hibernate session transactions

从我读到的内容中,当您尝试在提交前一个事务之前开始事务时会发生此异常。但是,我不明白为什么我会在这种情况下得到这个例外。

我有一个带有以下servlet的Web应用程序:

@RestController
public class Hello {

/***** DAO's *******/
@Autowired
CompteDAO compteDAO;


@RequestMapping("/")
public String index() {

    String response = "";   

    /***** COMPTE TEST *****/

    response = response + "======== COMPTE TEST ========= \n";

    response = response + "Compte list : \n";


   ArrayList<Compte> comptes = (ArrayList<Compte>) compteDAO.getAllComptes();

   for(int i = 0; i < comptes.size(); i++) {
       response = response + comptes.get(i).getNomUtilisateur() + "\n";
   }

   response = response + "\n" + "Compte name = ";       
    return response;
}

这是我的Compte对象:

public class Compte {

    public int id;
    public String nomUtilisateur;
    public String motDePasse;
    public int typeCompte;
    public String courriel;
    public String cleAPI;
    public boolean visibleLorsDeLaCreation;
    public int joursDisponibilite;
    public int heuresDisponibilite;


    public Compte(){

    }

    public Compte(String nomUtilisateur, String motDePasse, int typeCompte, String courriel, String cleAPI,
            boolean visibleLorsDeLaCreation, int joursDisponibilite, int heuresDisponibilite) {
        this.nomUtilisateur = nomUtilisateur;
        this.motDePasse = motDePasse;
        this.typeCompte = typeCompte;
        this.courriel = courriel;
        this.cleAPI = cleAPI;
        this.visibleLorsDeLaCreation = visibleLorsDeLaCreation;
        this.joursDisponibilite = joursDisponibilite;
        this.heuresDisponibilite = heuresDisponibilite;
    }
    /** Getters and setters omitted **/
}

这是我DAO的界面:

public interface CompteDAO {

    public List<Compte> getAllComptes();    
}

这是它的实施:

@Repository
public class CompteDaoImpl implements CompteDAO {

@Autowired
public SessionFactory sessionFactory;

public CompteDaoImpl() {
}   


@Override
public List<Compte> getAllComptes() {
    Session currentSession = sessionFactory.getCurrentSession();
    List<Compte> comptes;
    comptes = new ArrayList<Compte>(currentSession.createCriteria(Compte.class).list());
    return comptes;
}   

另外,这是我的Spring配置:

@Configuration  
@EnableTransactionManagement  
@PropertySource({ "classpath:application.properties" })  
@ComponentScan({ "ca.etsmtl.gti525, ca.etsmtl.gti525.pojo" })  
public class PersistenceConfig  
{  
  @Autowired  
  private Environment env;  

  @Bean  
  public LocalSessionFactoryBean sessionFactory() {  
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();  
     sessionFactory.setDataSource(restDataSource());  
     sessionFactory.setPackagesToScan(new String[] { "ca.etsmtl.gti525" });  
     sessionFactory.setHibernateProperties(hibernateProperties());
     sessionFactory.setMappingResources(new String[] {  "mapping/Compte.hbm.xml" });

     return sessionFactory;  
  }  

 @Bean  
  public DataSource restDataSource() {  
     BasicDataSource dataSource = new BasicDataSource();  
     dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));  
     dataSource.setUrl(env.getProperty("jdbc.url"));  
     dataSource.setUsername(env.getProperty("jdbc.user"));  
     dataSource.setPassword(env.getProperty("jdbc.pass"));  

     return dataSource;  
}

  @Bean
  public CompteDaoImpl compteDAO () {
      CompteDaoImpl compteDAO = new CompteDaoImpl();
      return compteDAO;
  }

  @Bean
  public SessionManagerFilter sessionManagerFilter () {
      SessionManagerFilter sessionManagerFilter = new SessionManagerFilter();
      return sessionManagerFilter;
  }

  @Bean  
  @Autowired  
  public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {  
     HibernateTransactionManager txManager = new HibernateTransactionManager();  
     txManager.setSessionFactory(sessionFactory);  

     return txManager;  
  }  

  @Bean  
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {  
     return new PersistenceExceptionTranslationPostProcessor();  
  }  

  Properties hibernateProperties() {  
     return new Properties() {  
        {  
           setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));  
           setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));  
           setProperty("hibernate.globally_quoted_identifiers", "true");  
        }  
     };  
  }  
}

关联的application.properties文件包含以下行:

# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/gti525
jdbc.user=root
jdbc.pass=vente

# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.current_session_context_class=thread

最后,我有跟随的servlet过滤器,在那里我开始事务:

@Transactional
public class SessionManagerFilter implements Filter {

    @Autowired
    SessionFactory sessionFactory;


    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
         try {  
                Session currentSession = sessionFactory.getCurrentSession();
                currentSession.beginTransaction();  

                // Call the next filter (continue request processing)  
                chain.doFilter(request, response);  

                // Commit and cleanup  
                sessionFactory.getCurrentSession().getTransaction().commit(); 

            } catch (StaleObjectStateException staleEx) {  
                // Rollback, close everything, possibly compensate for any permanent changes  
                // during the conversation, and finally restart business conversation. Maybe  
                // give the user of the application a chance to merge some of his work with  
                // fresh data... what you do here depends on your applications design.  
                throw staleEx;  
            } catch (Throwable ex) {  
                // Rollback only  
                ex.printStackTrace();  
                try {  
                    if (sessionFactory.getCurrentSession().getTransaction().isActive()) {  
                        sessionFactory.getCurrentSession().getTransaction().rollback();  
                    }  
                } catch (Throwable rbEx) {  

                }  

                throw new ServletException(ex);  
            }  
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

这是在web.xml文件中映射的,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>sitevente2</display-name>

     <filter>  
        <filter-name>SessionManagerFilter</filter-name>  
        <filter-class>ca.etsmtl.gti525.SessionManagerFilter</filter-class> 
        <!-- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    -->
    </filter>  

    <filter-mapping>  
        <filter-name>SessionManagerFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 


</web-app>

当在SessionManagerFilter的doFilter()方法中调用方法beginTransaction()时,我得到以下Stack Trace:

org.hibernate.TransactionException: nested transactions not supported
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:154)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
at ca.etsmtl.gti525.SessionManagerFilter.doFilter(SessionManagerFilter.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy73.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:120)
at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:95)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2016-03-14 22:14:32.120 ERROR 7284 --- [nio-8080-exec-2]     o.s.t.i.TransactionInterceptor           : Application exception overridden by commit exception

我不知道我做错了什么。必须有一些我不理解的框架。如果你能帮助我,我将非常感激。

谢谢! :)

2 个答案:

答案 0 :(得分:1)

好的,上面的代码有些问题。您似乎将Transactional会话与HTTP会话混淆。他们是两个不同的东西。 Transactional会话是数据库调用。您将数据库调用包装在事务中,以便在出现问题时回滚整个事件。如果您要使用RESTful架构,则不应该使用HTTP会话,因为HTTP会话意味着您在应用程序中的某个位置存储状态。 REST操作应该是幂等的(独立且可重复的)。使用RESTful架构,您应该能够执行相同的调用数千次并获得相同的结果,而不会影响应用程序的任何其他部分。

在Spring中,通常有3个单独的层。您的控制器管理特定对象的HTTP请求和响应,因此您将拥有CompteController和其他对象的控制器。这些控制器涉及对这些对象的RESTful操作。 GET,POST,PUT和DELETE请求由控制器处理。控制器通常通过调用服务类来完成此操作。服务类用于管理事务,操作对象和封装业务逻辑。 DAO类纯粹用于数据库访问。

您正在获取异常,因为您尝试在事务会话旁边使用HTTP会话。由于许多不同的原因,这是错误的,并且会导致许多问题,因为这不是@Transcational的使用方式。

我会按如下方式重构您的代码:

控制器:

@RestController
public class CompteController { 

   @Autowired
   private CompteService compteService;

   @RequestMapping(value="/", method=RequestMethod.GET)
   public List<Compte> getAllCompte() throws Exception {
       /** Because you've used `@RestController` you've indicated that you want your object return in JSON format by this method. **/
       return compteService.getAllCompte();
   }
   /** methods here to handle GET, POST, PUT and DELETE requests**/

}

服务层

public interface CompteService {

    public Compte getCompte(int id);

    public List<Compte> getAllCompte();

    /** Other methods to create, update, manipulate and delete Compte objects **/
}

服务实施

@Service
public class CompteServiceImpl implements CompteService {

    @Autowired
    private CompteDAO compteDao;

    @Override
    @Transctional
    public Compte getCompte(int id) {
        return compteDao.getCompte(id);
    }
    @Override
    @Transcational
    public List<Compte> getAllCompte() {
        return compteDao.getAllCompte();
    }

}

这里的@Transactional注释将被选中负责创建,打开,维护和关闭数据库连接的HibernateTransactionManager。这会发生在您注释@Transactional的方法周围。如果将@Transactional放在类上,那么所有类方法都将包装在事务中。如果抛出异常,则HibernateTransactionManager将回滚事务并将异常传播回控制器。

DAO:

public interface CompteDAO {

    public Compte findCompte(int id);

    public List<Compte> findAllCompte();

}

DAO实施:

@Repository
public class CompteDAOImpl implements CompteDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Compte> getAllComptes() {
        Session currentSession = sessionFactory.getCurrentSession();
        List<Compte> comptes = currentSession.createCriteria(Compte.class).list()
        return comptes;
    }
}   

您无需将CompteDAOImpl声明为@Bean,因为您使用的是@ComponentScan,它会选择使用@Controller注释的类,@RestController,{{ 1}},@Service@Repository和其他几个。这些课程可用于自动装配到其他课程中。

上面的代码分离使得单独测试DAO,服务和控制器变得非常容易。它还将应用程序的逻辑与从数据库中提取对象分开。如果您认为需要明确管理数据库连接,那么就会出现问题。

如果您特别想抓住@Component并在发生这种情况时采取其他措施,那么您可以执行以下操作:

StaleObjectStateException

进一步阅读Hibernate和Spring(披露:我在这个主题上创建的Q&amp; A):

答案 1 :(得分:0)

您在应用程序中使用两种不同的事务管理系统。

详细说明:

  1. 在SessionManagerFilter中使用@Transactional
  2. currentSession.beginTransaction();
  3. 我从未在过滤器上测试@Transactional,因为我通常在@RestController中启动我的事务,但这取决于你。