1

I have a Spring bean with @Transactional method.

public class ABean{
  @Transactional
  public void method aMethod(){
    //do some job with Hibernate.
  }
}

But now I need to call this method from another method which should be called not in Spring context (in Quartz context actually):

public class ABean implements org.quartz.Job{

  @Transactional
  public void method aMethod(){
    //do some job with Hibernate.
  }

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("start...");
    //@Transactional annotation is ignored here 
    //so I have 'Could not obtain transaction-synchronized Session 
    //for current thread' exception.
    aMethod();
    System.out.println("done");
  }
}

As I understand annotation @Transactional just somehow wraps method with some another code. So how I must wrap aMethod() call to call it exactly like Spring calls?

Ivan Zelenskyy
  • 659
  • 9
  • 26
  • Possible duplicate of [Spring @Transaction method call by the method within the same class, does not work?](http://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo) – Arjun Nov 23 '16 at 11:42

2 Answers2

2

You can use Transaction from Hibernate instead as you said this method will not run in Spring managed environment and use it pro grammatically. Create Session object from Hibernate SessionFactory. From Session you can get Transaction using session.beginTransaction(). Check out : Hibernate Docs

Goro
  • 516
  • 4
  • 15
1

Spring only adds its transactional logic when you call it from another bean. When calling a method from the same class, the annotation is ignored.

For you that means you should move aMethod() to another Bean and invoke it from your existing ABean.

Bob
  • 5,510
  • 9
  • 48
  • 80