Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the transactions rolled back even when propagation=Propagation.REQUIRES_NEW in second method in Spring service class?

Basic settings are all fine now and I started to try transactions. Struts+Spring+Hibernate annotation transaction manager. This is the sample code in Action, will call a service class:

    userService.addUser();

Here is the addUser() method in service class:

    @Transactional(value="deu"  )
    public void addUser() {     
        userDao.addUser();
        this.addUser2();

    }

First, I called addUser in userDao, which will insert a user. Second, I called addUser2 in another method in this service class.

    @Transactional(value="deu" , propagation=Propagation.REQUIRES_NEW  )
    public void addUser2()   {      
    //should be a new transaction and will not affect the previous one. 
            //this one will fail but should not affect the previous one.
        userDao.addUserFail();        
    }

And this one will failed due to null PK. I suppose the second call (addUser2) will fail but will not affect the previous one. However, the user is not inserted.

If I only call:

   @Transactional(value="deu"  )
    public void addUser() {     
        userDao.addUser();
        //this.addUser2();      
    }

It is working, meaning basic settings like database is not wrong.

Any idea?

like image 792
Aska Avatar asked Mar 09 '13 17:03

Aska


1 Answers

Spring's declarative transaction handling works using AOP proxies. When you get a tranasactional bean, you in fact get a proxy which wraps your bean instance, intercepts the method call, starts a transaction if necessary, then calls the actual bean's method, then commits or rollbacks the transaction if necessary.

But you're calling a method of your bean from another method inside the same bean, so the proxy is bypassed, and can't apply any transactional behavior.

Put the method in another bean, or use AspectJ, which instruments the byte code and can intercept intra-bean method calls.

For a more detailed explanation, see the Spring documentation.

like image 75
JB Nizet Avatar answered Nov 14 '22 21:11

JB Nizet