2017-03-20 7 views
3

私はTestNG + Spring + Hibernateを使用します。私は@BeforeClassでトランザクションを使用する場合 は、私が取得:TestNG @BeforeClassでトランザクションをどのように使用できますか?

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 

コード例:

@Transactional(transactionManager = "transactionManager") 
@Rollback 
@ContextConfiguration(locations = "/WEB-INF/testing/applicationTestContext.xml") 
@TestExecutionListeners(listeners = { 
     ServletTestExecutionListener.class, 
     DependencyInjectionTestExecutionListener.class, 
     DirtiesContextTestExecutionListener.class, 
     TransactionalTestExecutionListener.class, 
     SqlScriptsTestExecutionListener.class, 
     WithSecurityContextTestExecutionListener.class 
}) 
public abstract class ExampleOfTest extends AbstractTestNGSpringContextTests{ 
    @Autowired 
    private SessionFactory sessionFactory; 

    @BeforeClass 
    public void setUpClass() { 
     sessionFactory.getCurrentSession().beginTransaction(); // get HibernateException 
     sessionFactory.getCurrentSession().getTransaction().commit(); 
    } 

    .... 

} 

私は@BeforeClassでトランザクションを使用することができますどのように? すべてのクラステストで使用される1回限りのデータ入力にこれを使用したいと思います。

答えて

1

問題は、それがアクティブなトランザクションで実行する必要があり、

または

のような制限されている

// BMT idiom with getCurrentSession() 
try { 
    UserTransaction tx = (UserTransaction)new InitialContext() 
          .lookup("java:comp/UserTransaction"); 

    tx.begin(); 

    // Do some work on Session bound to transaction 
    sessionFactory.getCurrentSession().persist(...); 

    tx.commit(); 
} 
catch (RuntimeException e) { 
    tx.rollback(); 
    throw e; // or display error message 
} 

getCurrentSessionのようなものを試してみてください@EnableTransactionManagementは、あなたの春のコンテキストであるべきだろう。

これは役立つと思います。

関連する問題