Question

The project used Spring + Hibernate

Sample code:

public void method(){    
   try{  
     dao.saveA(entityA);  
     //condition may be throw RuntimeException;  
     dao.saveB(entityB);  
    }catch(RuntimeException e){  
     throw e;  
    }finally{  
      dao.saveC(entityC)  
    }  
}

Finally, just entityC will be saved in database in test.
I think saveA, saveB, saveC in the same transaction,they should not be committed.
In this case, I want to know why entityC is committed.
How does Spring do this in the finally block?

//-------------------------//
Actually, my question is that:how spring ensure the transaction committed in the finally block . will Spring be get a new connection in the finally block?

Was it helpful?

Solution

Spring has nothing to do with this, what you obtain is a behavior as required by JLS 14.20.2 Execution of try-catch-finally:

A try statement with a finally block is executed by first executing the try block. Then there is a choice...

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice...
    • If the catch block completes abruptly for reason R, then the finally block is executed...

In your code snippet, RuntimeException corresponds to "value V" in above quote.

Exception is thrown and caught in respective catch block, which then "completes abruptly" by re-throwing the exception - that is, throw e in your snippet corresponds to "reason R" in above quote.

Then, as required by language specification, "finally block is executed".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top