Search code examples
springhibernatejpatransactional

Spring @Transactional annotation behaves weird


I have the following method:

@Transactional
public void onEmailMessage() {

    this.departmentService.removeUserFromDepartments(user, depsids);
    this.departmentService.getDepartmentUsers(user.id); 
}

The weird thing when i invoke this method, the first line:

  this.departmentService.removeUserFromDepartments(user, depsids);

is called but the DB is not changing at all and the user is still connected to the deparment (many to many relation)

afterwards the method :

   this.departmentService.getDepartmentUsers(user.id); 

is called and returns users that are connected to the department including the removed user from line#1.

when the method returns - if i check the DB the user i removed is actually been removed from the table!

can i make the query return the actual updated values??


Solution

  • There is nothing weird about this. You are performing two different queries within the same transaction. Persistence context is updated, but the transaction hasn't been committed yet, and you can't see your changes after first line is finished. Transaction is a set of statements (in this case - statements created by those two methods of yours) which gets executed after commit is invoked. When the whole (onEmailMessage) method finished it's job, the transaction is committed and you are seeing the changes.

    The solutions would be:

    Make them as two separate transactions. For e.g:

    @Transactional
    public void removeUser(...) {
        someInstance.departmentService.removeUserFromDepartments(user, depsids);
    }
    

    And:

    @Transactional
    public List<?> getUsers(...) {
        return someInstance.departmentService.getDepartmentUsers(user.id);
    }
    

    Then the highest level would be onEmailMessage() method, which has to be non-transactional and in separate class then these two methods above. Call them both in this level and it will work.