2


class MyService {

public void a() { synchronized(somekey) { b(); } }

@Transactional(propagation = Propagation.REQUIRES_NEW) public void b() { ...do DB works... } }

My aim is

    1 - get the key
    2 - start transaction
    3 - commit transaction
    4 - release the key

When i call a() method from outside, transaction doesn't work.

Any suggestions ?

Thanks.

3
  • 1
    What does "doesn't work" look like? Exceptions and error messages would be helpful. Commented Sep 14, 2010 at 11:38
  • There is no error; just transaction doesn't start, every insert operation directly goes to Database Commented Sep 14, 2010 at 11:49
  • How did you configure you're transaction manager ? Commented Sep 14, 2010 at 12:41

5 Answers 5

6

Unless you're using code weaving, this can't work.

The default way Spring handles transactions is through AOP proxies. The call to a transactional method goes like this:

 caller --> ProxyClass.a() --> YourClass.a()

If you call another method on the same object, you're not going through the proxy, so there is no transactional behaviour.

 caller --> ProxyClass.a() --> YourClass.a() --> YourClass.b()

If you don't want to use AspectJ, you can get the proxy object using AopContext.currentProxy().

Sign up to request clarification or add additional context in comments.

Comments

2

Not 100% sure. I think all @Transactional calls must be done on the same thread that a transaction started on. I know for certain that @Transactional doesn't work across threads. (I guess by design)

Comments

1

If you want to call b() inside of a(), and you want to make b() transactional, you have to put it into separate class.

Comments

1

Method call to b() is internal call not on transactional proxy as said by Henning.

Whole thing is explained in this blog post.

Comments

0

I'm curious as to the nature of the key. Why is the service generating it? Wouldn't an alternative design put that in the database?

It's hard to tell exactly what's wrong without an error message.

2 Comments

There is no error; just transaction doesn't start, every insert operation directly goes to Database.
Also database may change according to location (customer), so i just want to solve it at Java side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.