سؤال

I have the following situation in my Java web app (Spring + JPA):

  1. I have method which persist an entity to the database
  2. Right after persist entity, I call notify() which is waking up another thread.
  3. The second thread is working with the entity i've just persisted.

So as a result I have: Second thread queries a new-persisted entity, but it is not there yet. So second thread sends query to the database faster then main thread persist it. If i add some timeout it works perfectly. But it is not a suitable solution for me. I guess I can check entitymanager with contains() method. But I am not sure how efficient it will be. I am quite new in this subject, so I would be glad to hear your advices.

p.s. I am using Spring framework, so persist and notify happend in one transaction (marked with @Transactional annotation). second thread does not have any @Transactional classes.

Thanks, Emily.

هل كانت مفيدة؟

المحلول 2

Real persist to the database happens only after commit of the transaction, as far it happens in @Transactional method . So I needed to call second thread after transaction commit and I was able to do it using TransactionSynchronizationManager and its afterCommit() method. Here is the link with all info and examples http://azagorneanu.blogspot.ru/2013/06/transaction-synchronization-callbacks.html Maybe it will be useful for somebody.

نصائح أخرى

Try using the Entity Listeners for being notified when an entity is persisted. You can read about entity listeners in the JPA Wiki Book, the Hibernate documentation and at www.objectdb.com.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top