Darwin Thamil E
Darwin Thamil E

Reputation: 51

@Transactional needs to rollback everything except one save in database

I have a method:

@Transactional
@Override
public void createFile(final String number) {
    try {
           //code to save values
           throw new Exception(number);
        } catch(Exception e){
             this.repository.save(e.getMessage());
     }
}

In the method createFile there are many database save operations which needs to rollback when an error occurs. Catch needs to save the error message in the table.

How can i rollback the whole transaction in case of Exception but still do that save/update this.repository.save(e.getMessage()); on the database? could anyone help me sort this out? Thanks in advance.

Upvotes: 4

Views: 863

Answers (1)

wilx
wilx

Reputation: 18228

I am assuming you are using Spring.

Split it into two methods. E.g., createFile with the try-catch which calls the other, e.g., createFileWorker with the //code to save values. Call createFileWorker from createFile. If both the methods are in the same class, e.g., MyService, you will have to use @Lazy to inject proxied MyService into MyService and you will have to call createFileWorker via this proxied lazy instance. The createFileWorker should be annotated with @Transactional(propagation=Propagation.REQUIRES_NEW).

@Service
class MyService {

private MyService self;

public MyService(@Lazy MyService self) {
  this.self = self;
}

@Transactional
void createFile() {
  try {
    self.createFileWorker()
  } catch (Exception ex) {
    this.repository.save(e.getMessage());
  }
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
void createFileWorker() {
  //code to save values
}

}

Upvotes: 4

Related Questions