2010-11-04 49 views
0
 

@Transactional 
public void start() { 
    ... 
    ... 
    int result = entityManager 
       .createQuery("update Users set name=" + value + " where user.id=5").executeUpdate(); 
    ..... 

} 
 

上面的代码给出了javax.persistence.TransactionRequiredException异常。在交易中间更新数据库,可能吗?

在交易中间更新数据库,可能吗?

有什么建议吗?

谢谢。

A.

我只是想知道

回答

4

这是由持久性提供抛出当需要事务,但不活跃运行时异常。交易是必需的,因为start方法被注释为交易。为了消除例外情况,您必须调查为什么该行被称为不在事务上下文中。

数据库更新可能在(不同的)事务期间是可能的。取决于由活动事务和事务策略锁定的表。但在这种情况下,您看起来像您需要激活交易之前您输入start方法。


随着JPA你会做这样的事情:

em = emf.createEntityManager(); 
tx = em.getTransaction(); 
tx.begin(); // now a transaction is active 
start();  // call your method 
// call other methods... 
tx.commit(); // now the update is actually done 
em.close(); 

注意 - 这是接近伪代码,异常处理缺少在这个例子。

+0

怎么样?一个例子,请...谢谢。 – Altug 2010-11-04 08:19:48