I am developing a Spring/Hibernate application and I am seeing some unexpected behaviour whilst trying ot make updates to existing objects.
Currently, I have a service class method that simply updates an object as follows:
@Transactional
public void updateToDoCompletion(long id, boolean completed){
ToDo todo = getEntityManager().find(ToDo.class, id);
if (todo!=null){
todo.setCompleted(completed);
}
}
My understanding is that a transaction is started around the method, the ToDo object is loaded (within the transaction) and then any changes that I make to that object will be persisted once the transaction has ended (in this case, the method is being called from outside a transaction, in my controller class, so I expect the transaction just to last for this method).
However, having run through the above, the changes to the object are never being persisted to the database.
Interestingly, this update at the end of the transaction is working elsewhere in almost identical setups (in terms of expected transactional boundaries etc), so I was experimenting with the code and updated the method as follows:
@Transactional
public void updateToDoCompletion(long id, boolean completed){
ToDo todo = getEntityManager().find(ToDo.class, id);
if (todo!=null){
todo.setCompleted(completed);
}
Team t = conService.loadTeam(50l);
t.setDescription("test description!");
}
This time, after making changes to the original object, I have loaded a different object, and made a change to that – I did this as the only difference I could see to other methods that were working as expected were they made calls to Transactional methods in other classes (so the added code, conService.loadTeam(50l) is a transactional method in another service class). Now, the original changes to the ToDo object are being persisted as I hoped, but the changes to the Team object are not.
So my questions are:
- Have I wildly misunderstood some concept of the hibernate transactions?
- Why, on adding the call to the other transactional conService class does my original object now start getting persisted
- Why isnt the Team object changes getting persisted? (obv I dont want to make this code in here, but interested to understand exactly what is going on)
Thanks
Ok, it seems as though the addition of the call to the other service class was a red herring – it seemed that a lot of the persistence was being a bit flaky, and if I clean the project and restart the server then the original code works correctly.
Has anyone else found this? I’m using Elcipse Gallileo and Tomcat.