Reputation: 3616
My application has a delete user option. Now in order to check concurrency condition I tried the following use case
org.hibernate.StaleObjectStateException
.. which is right .. since I am trying to delete an object which doesn't exists. But I am not able to catch this exceptiontry{
getHibernateTemplate().delete(userObj);
} catch (StaleObjectStateException e) {
e.printStackTrace();
}
How do i catch this exception ??
Upvotes: 3
Views: 2224
Reputation: 691735
You won't be able to catch it there, because it's not the delete call that throws the exception, but the flush of the session, which happens later (before the execution of a query, or before the transaction commit).
You should not catch this exception anyway, because when Hibernate throws an exception, you can't continue using the session anymore: it's in an unstable state. The only part of the application where such an exception can be caught is outside of the transaction, in order to display an error message to the user (or retry, but this won't be possible in this particular case).
Upvotes: 6
Reputation: 718798
The code in your question looks right on the face of it.
If that delete call actually throws that exception when executed, then your code will catch it. If it doesn't then the exception is actually being thrown in a different place ... or the exception that is being thrown is a different one.
I'd temporarily replace the catch with a catch of java.lang.Throwable
to see if some other exception is propagating at that point. And add a trace print to see if the code is executing at all.
If you already have a stack trace, that will tell you where the exception is being thrown unless something really tricky is going on. You just need to catch it further up the stack.
Upvotes: 0
Reputation: 15628
You are catching StaleObjectStateException instead of StaleStateException :-)
UPDATE: have a look at the stacktrace; assuming you're working in a transaction the exception might only be thrown when the transaction is committed.
Upvotes: 0