0

I have a DAO class where I have 2 methods annotated with the Spring @Transactional annotations, as follows:

public class ClassDAO {
    @Transactional
    public void save() throws Exception {

    }

    @Transactional
    public void save2() {

    }
}

I want those 2 methods to be part of the same transaction so if any method fails, the whole transaction is rolled back.

These methods are being called from the service layer, as follows: @Autowired private ClassDAO dao;

@Transactional
public void processDAO() {
    dao.save();
    dao.save2();
}

I'm using @Transactional annotations on service layer since I've read this is the best approach, but on the other hand I've read @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext, so if this is true, that would explain why the @Transactional annotation is not working on the service layer.

I have one questions:

If @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext, then how is it that it is a good practice to place Transactional annotation on service layer?

Thanks and best regards.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Henry
  • 67
  • 5
  • What does mean by not working? any exception/error? – Saravana Jul 12 '16 at 01:34
  • If any RuntimeException is thrown in save2() method, save1() is not being rolled back, that makes me think a transaction has not been started. If instead of doing this, I create a public and transactional method in the DAO class that calls save1 and save2, and call this new DAO method from the service class, then a transaction is started. – Henry Jul 12 '16 at 01:55
  • @Brad I think this question helps you http://stackoverflow.com/q/1079114/4934505 – Veeresh123 Jul 12 '16 at 06:02
  • Your dao shouldn't be transactional so remove the `@Transactional` from the dao. If you don't have a transaction you will get a nice exception, which basically indicates an issues with your configuration. And I guess you have a component scan in place that is scanning for the same components twice. – M. Deinum Jul 12 '16 at 06:37

0 Answers0