繁体   English   中英

休眠:在其他线程中查找刚刚持久化的对象

[英]Hibernate: Find just persisted object in different thread

我的应用程序中有多个线程-其中一个正在等待数据库中的某些更改通知。 我的问题是,一旦我持久化了某个对象并通知了另一个线程-当它自上次更改以来在数据库中查询新对象时,就找不到持久化的对象。

  @Transactional()
  public void persistMyEntity() {
      // persisting and notifying from first thread
      Entity myEntity = new Entity();
      em.persist(myEntity)
      em.flush();
      someOtherBean.notifyChange();
  }
  ...

以下bean应该被唤醒:

  public class SomeOtherBean {

      public void notifyChange() {
          currentThread.interrupt();
      }


      public void run() {
          currentThread = Thread.currentThread();

          while(true) {
              ...
              try {
                  Thread.sleep(VERY_LONG_TIME);
              } catch (InterrupedExcdeption e) {
                  // we don't care
              }

              findNewPersistedObjects();
              // nothing is found
          }
      }
  }

如果我重新启动线程,它将正确找到新对象。

编辑:拆分事务方法没有任何区别:

  public void persistMyEntity() {
      proxy(this).persistMyEntityInternal();
      someOtherBean.notifyChange();
  }

  @Transactional
  public void persistMyEntityInternal() {
      // persisting and notifying from first thread
      Entity myEntity = new Entity();
      em.persist(myEntity)
      em.flush();
  }
  ...

您的问题是事务划分。

您在事务完成之前通知其他线程。 仅当创建数据的事务结束(带有提交)时才可以查询数据库中的数据(某些数据库有一些例外,但我不会对此进行深入介绍)。

为了解决您的问题,您必须先提交事务,然后再从另一个线程查询它。

您可以向TransactionSynchronization注册一个TransactionSynchronizationManager 当trx成功提交后,这可以让您回叫。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM