سؤال

I am banging my head on an issue with OpenJPA.

I have a method:

public void update() {
    System.out.println("START: Update...");
    updateEmployee(employee);
    updateStudent(student);
    System.out.println("END: Update...");
}
updateEmployee(employee) {
   employeeDAO.update(employee);
}

updateStudent(student) {
    studentDAO.update(student);
}

But when I run this I am getting logs like this:

START: Update...
update com.sk.entity.Employee e set ...
update com.sk.entity.Student s set ...
END: Update...
openjpa.jdbc.SQL - executing prepstmnt 2036496738 UPDATE STUDENT SET...
openjpa.jdbc.SQL - executing prepstmnt 2036496738 UPDATE EMPLOYEE SET ...

Here I am still not getting:

  • why the update queries are not executed as soon as I am calling updateEmplyoee method. You can see the log that the sql are printed after my log statement "END: Update..."

  • why STUDENT table is getting updated first. As per method calling I am calling updateEmployee at first

Can anyone please reply if you know what I am missing.

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

المحلول

It is about transaction handling. Your transaction usually starts when calling an EJB method from a non EJB environment and finishes at the end of the same EJB method. So updateEmployee and updateStudent runs in the same EJB (JTA) transaction.

When calling update(), the EJB transaction starts. When calling updateEmployee and updateStudent, changes are saved in memory. At the end of the update() method, when the transaction seems successful, OpenJPA starts to persist all non-persisted changes from memory to the database in any order. If persisting these changes succeeded, then sends a commit to the database. If database commit succeeded, then it finishes the EJB transaction with success.

If you want to persist the data in the same order, you can use the flush() method of the EntityManager. Or you can start a new transaction for updateStudent and updateEmployee methods:

@TransactionAttribute(REQUIRES_NEW)
public void updateStudent(...) {...}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top