Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibernate:在不同的线程中查找刚刚持久化的对象_Java_Multithreading_Hibernate - Fatal编程技术网

Java Hibernate:在不同的线程中查找刚刚持久化的对象

Java Hibernate:在不同的线程中查找刚刚持久化的对象,java,multithreading,hibernate,Java,Multithreading,Hibernate,我的应用程序中有几个线程,其中一个线程正在等待数据库中某些更改的通知。我的问题是,一旦我持久化某个对象并通知另一个线程,当它查询数据库中自上次更改以来的新对象时,就找不到持久化的对象 @Transactional() public void persistMyEntity() { // persisting and notifying from first thread Entity myEntity = new Entity(); em.persis

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

  @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();
  }
  ...

您的问题是事务划分

在事务完成之前通知其他线程。数据库中的数据只能在创建数据的事务结束(通过提交)时查询(有些数据库有一些例外情况,但我不会对此进行深入讨论)


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

您可以使用
TransactionSynchronizationManager
注册
TransactionSynchronization
。这允许您在trx成功提交时被召回

我实际上如何提交事务?
em.flush
位于用
@Transactional
@Vojtěch注释的方法中。当该方法离开时,事务被提交。因此,您必须在带有事务性注释的方法之后查询方法。