Aditya
Aditya

Reputation: 1043

Hibernate @Transactionl error

Hi Face an wiered problem using Spring/JPA Hibernate.

I have two methods in service class methodA() and methodB()

@Transactional
methodA(){
    for(){
        methodB();
    }

    some other database operations.
}

@Transactional
methodB(){
    database Update/Insert Operations.
    save();
}

As above I invoke methodB from MethodA in a loop. If any operations from loop fails or database operations outside the loop fails, I was expectiong the trasnastion to rollback as methodA() itself is transactiona.

But I face wiered problem I see the data gets commited to database immediately after methodB() is finished and is not rolledBack even after throwing exception from methodA().

I also tried removing the transational from methodB(), aslo tried propogation = NESTED/REQUIRED/MANDATORY. But nothing seems to work.

Upvotes: 0

Views: 73

Answers (2)

Vineeth Bhaskaran
Vineeth Bhaskaran

Reputation: 2281

I think You have declared the @Transactional in DAO layer method.Here after executing that method it will commit/roll back to the DB. Define a method in service layer which is calling both methods and declare @Transactional annotation for that method and remove the @Transactional from DAO layer.Then the DB transactions(commit/rollback) will occur only after executing that service layer method.so some error in any method the DB rollback will happen.

Service Layer method will look like this

 @Transactional
public methodTest(){
        methodA();
        methodB();
  }

Upvotes: 1

Shailendra
Shailendra

Reputation: 9102

This is not how transactions work when using Spring.The transactional method must be called from outside and not within other method. The reason is that in your case Spring would not be able to apply transactions via AOP proxy since call to methodB is directly from methodA and Spring would have no means to apply the transactional aspect before methodB gets called. For more information have a look here in section "Understanding AOP proxies" and also here in section 10.5.1

Upvotes: 2

Related Questions