VKP
VKP

Reputation: 658

How i can do Rollback insert and Delete statements executed

Hi I have lot of delete statements followed by lot of insert statements. How i can do rollback of all statements in case of any failure happening during any statement execution . Ex : i have 10 delete statements and followed by 10 insert statements . If my last insert statement failed i need to roll back all delete and insert statements happend . Which would be the easiest way to achieve this ?

Upvotes: 0

Views: 882

Answers (1)

Abhinaba Chakraborty
Abhinaba Chakraborty

Reputation: 3671

Two ways to do this:

  1. Putting Spring's @Transactional annotation on top of your method inside which you are performing the inserts/deletes
  2. Manually creating and managing the transaction

First way is recommended.

Examples:

Using purely Spring:

@Service
public class MyPersistenceService {

  @Autowired
  private MyRepository mytRepository;

  @Transactional
  public void myLogic() {
     //perform all the inserts and deletes
  }

}

Using Hibernate with Spring:

@Component
public class MyRunner implements CommandLineRunner {


 @PersistenceContext
 private EntityManager entityManager;

 @Override
 @Transactional
 public void run(String... args) throws Exception {
   Book book = new Book();
   book.setId(1L);
   book.setAuthor("author");
   book.setTitle("title");
   entityManager.merge(book); //an insert statement

   entityManager.remove(book); //a delete statement
 }
}

Second way is a very crud way to do this , since you are already using Spring. Here is a code snippet to do that:

Session session = null;  
Transaction tx = null;  
  
try {  
  session = sessionFactory.openSession();  
  tx = session.beginTransaction();  
  //Your insert and delete statements 
  
  tx.commit();  
  
}catch (Exception ex) {  
  ex.printStackTrace();  
  tx.rollback();  
}  
finally {
  session.close();
} 

Upvotes: 1

Related Questions