3

Lets say I have three Jobs currently running, two of which are identical... so:

CrawlJob job1 = new CrawlJob();
CrawlJob job2 = new CrawlJob();
CurrentJob job3 = new CurrentJob();
job1.now()
job2.now()
job3.now()

If I do the following in job1:

JPA.em().flush();
JPA.em().clear();

Will that also detach all the entities that job2 and job3 are currently processing? Meaning if I'm passing around an entity/Model Object in job2/job3 that I looked up in the database, is job2/job3 liable to break because the Object will have just been detached from the session?

Similarly, lets say I do the following in job1:

long id = 123
User user1 = new User(id);
user1.save();

And then in job2 or job3 I do:

User user2 = User.findById(id);

will user2 be equal to "null" or equal to "user1"? Meaning, even though user1 has NOT yet been flushed/committed to the database, will job2 or job3 be able to look it up by Id?

I think what both these questions are getting at is whether Jobs (regardless of whether they are instantiations of the same Job or a different Job) share EntityManagers and thus .em().flush(), .em().clear() or .em().getTransaction().commit() OR Model.save() will affect all the Jobs at the same time?

1 Answers1

3

Jobs start their own jpa transaction and your entities will not actually be persisted until the transaction completes.

So job2 will not see the change made by job1 unless job 1 completes when job2 loads the entity.

If you wanted to commit the data whilst jobs1 is still running you can commit the transaction in job1 and start a new one with something like:

    JPA.em().getTransaction().commit();
    JPA.em().getTransaction().begin();
    JPA.em().flush();
    JPA.em().clear();
emt14
  • 4,846
  • 7
  • 37
  • 58
  • Lets say job1 and job2 (2 instantiations of the same Job) call the same method in 'doJob()' called processQueue(). So if within 'processQueue(){}' I do 'JPA.em().getTransaction', your saying that a different Transaction would be returned depending on whether job1 or job2 called processQueue? Similarly it sounds like your saying doing 'JPA.em().clear' in job1 will have no effect on the entities that may currently be attached in job2. – HelpMeStackOverflowMyOnlyHope Mar 25 '12 at 13:36
  • also in the example you provide, why do you do JPA.em().flush() after JPA.em().getTransaction().commit()? Doesn't the commit() flush/synch everything with the database already to be able to write out? – HelpMeStackOverflowMyOnlyHope Mar 25 '12 at 13:37
  • Thanks for the answer i have lots of entities that needs to be saved immediaetly. So i've put this code into a void names "saveEntities" and call it from wherever i need an imeediate update. – dreampowder Nov 21 '12 at 11:34
  • 1
    I have noticed that sometimes it is simpler to use straight JDBC for data insert in my jobs. You do get better performance and more control over the data persistence. – emt14 Nov 25 '12 at 10:00