【问题标题】:JPA : multiple transactionsJPA:多笔交易
【发布时间】:2012-02-18 16:12:24
【问题描述】:

我正在尝试使用同一个事务实体进行 2 个不同的数据库调用。我知道我可以在begin()commit() 之间进行两次审问,但我只是出于教育目的尝试这样做。

EntityTransaction transaction = em.getTransaction();
EventService eventService = new EventService();
transaction.begin();
Event currentEvent = eventService.read(eventId);
transaction.commit();

if (currentEvent != null){
    CommentService commentService = new CommentService();
    transaction.begin();
    commentList = commentService.getList(1, id, 50);
    transaction.commit();
}

这段代码抛出:

异常描述:事务当前处于活动状态

知道我正在尝试使用begin() 处理已打开的事务,这很正常。

排除第二个transaction.begin() 并在我必须使用数据库时只使用commit() 是否正确?

乐: 我正在使用 EclipseLink 和 RESOURCE_LOCAL

【问题讨论】:

  • 如果在第一个 commit() 和第二个 begin() 之间从 EntityManager 重新获取事务会发生什么?
  • 同样的事情发生了。在第一个 .begin() 之后, .isActive() 将始终返回 true,直到我关闭 EntityManager。
  • 你能打印出 em.getClass() 和 transaction.getClass() 以查看正在使用的实现吗? EclipseLink 的事务实现将在 commit() 的 finally 块中将事务标记为不活动,因此它可能是一个包装器没有直接传递调用。您使用的是哪个版本的 EclipseLink?

标签: java jpa transactions eclipselink


【解决方案1】:

奇怪。这应该有效。您使用的是哪个 JPA 提供程序?也许启用日志记录以查看发生了什么。

【讨论】:

  • EclipseLink,事务类型为 RESOURCE_LOCAL
【解决方案2】:

发生这种情况是因为 transacton-type 设置为 RESOURCE_LOCAL。 在这种情况下,您必须创建一些应处理EntityManagerEntityTransactionSingleTon 类。

【讨论】:

    【解决方案3】:
    private static EntityManager picassoEm = null;
    
    public static synchronized boolean insertToDB(EntityObject eobj) {
        try {
            if (picassoEm == null) {
                picassoEm = JPAUnit.getEntityManagerFactoryPicasso().createEntityManager();
    
            }
            EntityTransaction eT = picassoEm.getTransaction();
            eT.begin();
            picassoEm.persist(eobj);
            eT.commit();            
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    
    }
    

    JPAUnit 就是你自己的工厂

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 1970-01-01
      • 2021-04-22
      • 2018-10-03
      • 1970-01-01
      • 2013-10-28
      • 2013-08-15
      • 2022-11-02
      • 2019-07-16
      相关资源
      最近更新 更多