0

I have a service which calls other services to perform DB operations. I have added a Transactional annotation on the method.

@Service
class myService {

    @Autowired Service1....

    @Transactional
    public void saveData(String data) {
        data = service1.changeData(data);
        dao1.save1(data);
        dao2.save2(data);
    }
}

@Service
class Service1 {
    .
    .
    .
    public String changeData(String data) {
        return dao3.getChangedData(data);
    }
}

@Repository
class dao1 {
    public void save1(String data) {
        // INSERT DATA ...      
    }
}

@Repository
class dao2 {
    public void save2(String data) {
        // INSERT DATA ...      
    }
}

@Repository
@Transactional
class dao2 {
    public String getChangedData(String data) {
        // Get Data...      
    }
}

The problem is if something goes wrong in save2() method called from myService, the data inserted in save1 is not rolledback in the database. It still persists in the DB. Any idea why is this not working?

Thanks!

Sercan
  • 4,739
  • 3
  • 17
  • 36
inquisitive
  • 135
  • 2
  • 11
  • I don't think the transactional status is being inherited by the rest of the method calls and its bound only to the scope of `saveData` method unless manually added! Have you tried something like what is described here https://stackoverflow.com/a/50833103/3408204 ? – Nergon Dec 20 '21 at 08:47
  • How do you call saveData ? inside myService? – Ori Marko Dec 20 '21 at 08:54
  • By default, Spring automatically rollback only on unchecked exceptions, see [docs](https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative-rolling-back). If your **something wrong** in dao2 is a checked exception, this might be your problem. – Baptiste Beauvais Dec 20 '21 at 10:54
  • @user7294900 Yes inside myService – inquisitive Dec 20 '21 at 11:24
  • you can't use Transactional method when called in same class, because it should go through a proxy – Ori Marko Dec 20 '21 at 11:43

0 Answers0