Declarative Transaction Management Example in Spring

Declarative Transaction

This tutorial shows an example on declarative transaction management in Spring framework. You may also want to know about Spring Transaction or Declarative Transaction management in Spring. Here I will create annotation based Spring stand alone and Spring Boot applications to create Declarative Transaction Management example in Spring framework. Here I will use H2 in-memory database to create the example.

This example is completely Java based configuration and does not use any XMl configuration. I am also going to show you how to configure build.gradle script for gradle based project and pom.xml file if you are using maven as a build tool.

Related posts:

Prerequisites

Java 8/11/19, Spring Boot 2.3.4/3.1.3, MySQL 8.1.0

Project Setup

Create a maven based Spring Boot project in your favorite IDE or tool. The project name is spring-declarative-transaction.

For the maven based project then you can use below pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-declarative-transaction</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>19</maven.compiler.source>
		<maven.compiler.target>19</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.3</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.31</version>
		</dependency>

                <!--<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>-->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Application Config

The application.properties file is kept under the src/main/resources folder to configure the datasource details.

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/roytuts
spring.datasource.username=root
spring.datasource.password=root

SQL Scripts

As I am using H2 and MySQL database to create example, so I will create table and insert data some sample data using SQL scripts for H2 database. These SQL scripts are kept under classpath directory src/main/resources/sql.

Table Script

Create below table SQL script – table.sql and put it under src/main/resources/sql directory.

CREATE TABLE `item` (
  `item_id` int(10) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(45) NOT NULL,
  `item_desc` text,
  `item_price` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`item_id`)
);

If you are using MySQL database then you can use the following table creation command:

CREATE TABLE `item` (
  `item_id` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
  `item_name` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
  `item_desc` text COLLATE utf8mb4_unicode_ci,
  `item_price` double COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  PRIMARY KEY (`item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Insert Script

Create below data.sql script and put it under src/main/resources/sql directory.

insert into `item`(`item_id`,`item_name`,`item_desc`,`item_price`)
values (1,'CD','CD is a compact disk',100),
(2,'DVD','DVD is larger than CD in size',150),
(3,'ABC','ABC test description',24),
(4,'XYZ','XYZ test description',25.32),
(5,'CD Player','CD player is used to play CD',30.02),
(6,'New Item1','New Item1 Desc',125);

Spring Config Class

Create Spring configuration class to create datasource, jdbc template, configuration for base package etc.

The following configuration class can be used for H2 database. For MySQL there is no need to create any configuration class and Spring Boot’s auto configuration feature will be used to create a datasource automatically from the standard naming convention in the application.properties file.

@Configuration
public class Config {

    @Bean
    public DataSource dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2) // .H2 or .DERBY, etc.
                .addScript("sql/table.sql").addScript("sql/data.sql").build();
        return db;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

}

In the above class I have used annotation @Configuration to indicate it is a configuration class.

I have created two beans – Datasource and JdbcTemplate, which are required to connect to the database and perform database operations.

Model Class

The below model class is used to represent each row of the table data to corresponding Java class attributes.

public class Item {

    private Long itemId;

    private String itemName;

    private String itemDesc;

    private Double itemPrice;

    // getters and setters

    @Override
    public String toString() {
        return "Item [itemId=" + itemId + ", itemName=" + itemName + ", itemDesc=" + itemDesc + ", itemPrice="
                + itemPrice + "]";
    }

}

Row Mapper

I have created model class in the above but I need to map each row column with Java class attribute and for that you need Row Mapper class.

public class ItemRowMapper implements RowMapper<Item> {

    @Override
    public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
        Item item = new Item();
        item.setItemId(rs.getLong("item_id"));
        item.setItemName(rs.getString("item_name"));
        item.setItemDesc(rs.getString("item_desc"));
        item.setItemPrice(rs.getDouble("item_price"));
        return item;
    }

}

Notice in the above class I am mapping the correct data type for each column value with Java class attribute.

DAO Class

You need to interact with database, so you need to create DAO class or Repository class for performing database operations.

Create a class with @Repository annotation to auto-pickup by Spring container. You may also use @Component annotation if you think @Repository is not relevant on this DAO class.

@Repository
public class ItemDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Item> getItems() {
        String sql = "SELECT * FROM item";
        List<Item> items = new ArrayList<>();
        items = jdbcTemplate.query(sql, new ItemRowMapper());
        return items;
    }

    public void addItem(Item item) {
        String sql = "INSERT INTO item(item_id, item_name, item_desc, item_price) VALUES (?,?, ?, ?);";
        jdbcTemplate.update(sql,
                new Object[] { item.getItemId(), item.getItemName(), item.getItemDesc(), item.getItemPrice() });
    }

    public void updateItem(Item item) {
        String sql = "UPDATE item SET item_name=?, item_desc=?, item_price=? WHERE item_id=?;";
        jdbcTemplate.update(sql,
                new Object[] { item.getItemName(), item.getItemDesc(), item.getItemPrice(), item.getItemId() });
    }

    public void deleteItem(Item item) throws Exception {
        String sql = "DELETE FROM item WHERE item_id=?;";
        jdbcTemplate.update(sql, new Object[] { item.getItemId() });
        throw new Exception();
    }

}

In the above DAO class, I have thrown new Exception() from deleteItem() method even after deletion of an item to show you that the data gets rolled back on Exception.

Ideally you should code to interface to achieve loose coupling but here for showing an example I have used class as a DAO.

Service Class

Create below Spring service class to perform business logic. I annotated the class using @Service to indicate it as a service class.

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ItemService {

    @Autowired
    private ItemDao itemDao;

    @Transactional(readOnly = true)
    public List<Item> getItems() {
        return itemDao.getItems();
    }

    public void addItem(Item item) {
        itemDao.addItem(item);
    }

    public void updateItem(Item item) {
        itemDao.updateItem(item);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteItem(Item item) throws Exception {
        itemDao.deleteItem(item);
    }

}

Look in the above class, I have put @Transactional annotation on the service class to work with several DAO classes to make a unit of work for service class. Because you may have several DAO classes, injected into a Service, that need to work together in a single transaction.

Transactional Annotation

This @Transactional annotation is for declarative transaction management in Spring application.

You can put put @Transactional annotation at class level or at method level. If you put @Transactional annotation at class level then it wraps all the method in a transaction scope. If you put @Transactional annotation at method level then it works with the particular method on which it is applied.

You can also put @Transactional annotation at class and method levels at the same time and in this case @Transactional annotation will be applied for all the methods with similar behavior except the methods for which you have applied @Transactional annotation at method level will have different behavior.

@Transactional annotation has several properties such as readOnly, isolation, propagation, rollbackFor, noRollbackFor etc. These properties can be used to control the behavior and communication with other transactions.

You can use @Transactional(readOnly=true) for select queries and @Transactional for insert and update queries because by default readOnly=false. And for reading data you don’t need to use transaction as there is no chance of overwriting data.

Another two important properties are rollbackFor and noRollbackFor – used for if a class throws exception the transaction will be rolled back for that exception class and rollback will not happen for that exception class respectively.

I have written deleteItem() to throw an Exception so that I can show you how the data is rolled back on Exception.

Spring Boot Main Class

As you know for stand alone Spring application you need to have main class or Junit class to test your application. Here I am creating main class to test the application. I am also creating Spring Boot main class to test the application.

@SpringBootApplication
public class SpringDeclarativeTransactionApp implements CommandLineRunner {

    @Autowired
    private ItemService service;

    public static void main(String[] args) {
        SpringApplication.run(SpringDeclarativeTransactionApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("----Available Items----");

        List<Item> items = service.getItems();
        items.forEach(i -> System.out.println(i));

        System.out.println();

        try {
            Item delItem = new Item();
            delItem.setItemId(6l);
            service.deleteItem(delItem);

            System.out.println("Item Successfully Deleted.");
        } catch (Exception ex) {
            System.out.println("Item was not deleted.");
            System.out.println("Transaction rolled back due to Exception.");
        }

        System.out.println();
    }

}

You get the service class bean and you need to call the deleteItem() and getItems() methods to delete an item and show all items, respectively.

Testing the Application

Run the above main class you will see the following output on the Eclipse console:

----Available Items----
Item [itemId=1, itemName=CD, itemDesc=CD is a compact disk, itemPrice=100.0]
Item [itemId=2, itemName=DVD, itemDesc=DVD is larger than CD in size, itemPrice=150.0]
Item [itemId=3, itemName=ABC, itemDesc=ABC test description, itemPrice=24.0]
Item [itemId=4, itemName=XYZ, itemDesc=XYZ test description, itemPrice=25.32]
Item [itemId=5, itemName=CD Player, itemDesc=CD player is used to play CD, itemPrice=30.02]
Item [itemId=6, itemName=New Item1, itemDesc=New Item1 Desc, itemPrice=125.0]

Item was not deleted.
Transaction rolled back due to Exception.

So from the above output you see that you had initially six items and an item was not deleted using deleteItem() method because of exception.

So if you again call getItems() method you will see six items will be displayed on the console.

Hope you got an idea on Declarative Transaction Management Example in Spring.

Source Code

Download

0 thoughts on “Declarative Transaction Management Example in Spring

Leave a Reply

Your email address will not be published. Required fields are marked *