Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reverting incomplete database modifications using transactions


Some database modifications involve several SQL queries, for example, inserting an object with attributes spread across several tables. If one of the queries fails, we would want to undo any previous ones that were successful.

How to do it…

Here are the steps to make DAO methods transactional:

  1. Add @EnableTransactionManagement to the Spring configuration class:

    @Configuration
    @EnableWebMvc
    @EnableTransactionManagement
    @ComponentScan(basePackages = {"com.spring_cookbook.controllers", "com.spring_cookbook.dao"})
    public class AppConfig {
    …
  2. Add a DataSourceTransactionManager bean to the Spring configuration:

    @Bean
    public DataSourceTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
      transactionManager.setDataSource(dataSource());
      return transactionManager;
    }
  3. Annotate the DAO class with @Transactional:

    @Repository
    @Transactional
    public class UserDAO {
    …

How it...