views:

44

answers:

1

Let's say I have the following code:

public void doSomething() {
    // begin transaction

    // do stuff 1
    ...

    // update a row which must be committed now
    ...

    // do stuff 2
    ...

    // commit transaction
}

I've kept the large amount of work on the database in the one method to simplify the pseudo code. However, basically I have a series of database work that I won't want to commit until the end. In the middle of the transaction above, I need to commit something to a row without committing the rest of the transaction. How would I commit that small bit of work without affecting the rest of the transaction?

+2  A: 

Usually you accomplish this simply by grabbing another connection and performing the work on the other database connection. You may or may not need to manage database isolation levels to have the visibility you desire. This is how, for example Propagation.REQUIRES_NEW works in Spring. (edit: one notes you tagged the question Hibernate. Essentially, you make an entirely new session/entitymanager and do the separate work with that one. This will have some probably unexpected results for object state across the boundaries. If you load something from one session and try to keep using it across the boundary into the other it's liable to explode on you. You will need to be careful to manage it properly and keep track of what is managed by which Session.)

Affe
I tried isolating it like you said by doing this: Session session = factory.openSession(); session.beginTransaction(); // save something session.getTransaction().commit(); - this doesn't seem to commit the change.
digiarnie
The actual code that doesn't work would be helpful. But it sounds like you're trying to change a save made to an object that was already loaded by the outer session. You need to make sure your object is attached to the inner session before making changes to it, in order for it to commit them.
Affe
From a simple test point of view, I think I may have finally gotten it to work. I updated my previous example so now it looks like this: Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); // save something transaction.commit(); - I'm not sure why this technique works and why the previous didn't.
digiarnie
nope, silly me. Because it was a different session object, the reason why it didn't work when I first attempted it was because I called save(). My second attempt had the change of saveOrUpdate() - that's why it worked. I re-ran my simple test with my original example using 'session.getTransaction().commit()' and it worked too. Thanks for your help Affe!
digiarnie