nightograph
nightograph

Reputation: 2269

How to save a jpa object within a for loop

I have a list of users which I would like to send invite emails to, after I send the email, i would like to save that person in a separate table so incase server goes down we won't be sending double emails since we know who was the last person we sent email to. this is the code:

@play.db.jpa.NoTransaction
public void sendInvite() {
    Long lastUser = (Long) User.find("select MAX(id) from User").fetch().get(0);
Long lastId = (Long) Contact.find("select MAX(id) from Contact").fetch().get(0);

    for (i=lastContacted; i < totalNumUsers; i++) {
        UserContact  contact = new UserContact();
        contact.firstName = user.firstName;
        contact.lastName = user.lastName;
        contact.email = user.email;
        if (validateEmail(user) == false) {
            continue;
        }
       sendInviteEmail(user);
       saveContact(contact); //THIS DOESN'T TAKE PLACE UNTIL END OF THE LOOP
       Thread.sleep(2000);
    }
}

The Problem is that the saved contact, is not getting saved in the database until the end of the for loop. i have tried:

contact.em().persist(contact);
contact.em().flush();

but that is not working either
* i would also want to add that the method is being run from a Job and not from a Controller.

Upvotes: 1

Views: 2875

Answers (1)

JB Nizet
JB Nizet

Reputation: 691933

If you do all this in a transaction, and the server goes down, the transaction won't be committed, and even if you flush during the transaction, nothing will be written to the database. Foe each and every contact, you need to open a new transaction, save the contact in this new transaction, then commit the transaction.

Upvotes: 2

Related Questions