Spring Road (40) - declarative transaction management with @ Transactional is so simple

Keywords: Database JDBC Java MySQL

Simple enough

To be honest, to implement transaction management and add an annotation to a method, the method automatically implements transactions, which is simple enough. I can't think of anything simpler.

This annotation is @ Transactional, which is so excellent. Declarative transaction management is a way to enable transactions by adding annotation declarations to methods (or classes).

Declarative transaction instance

First, normally write data object Do corresponding to database table blog:

package org.maoge.transactionaldemo;
/**
 * @theme Data object blog
 * @author maoge
 * @date 2020-01-27
 */
public class BlogDo {
	private Long id;
	private String title;
	private String author;
	private String content;
	// Omit get
}

Second, write the database operation class, and operate the database through NamedParameterJdbcTemplate.

package org.maoge.transactionaldemo;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
/**
 * @theme DAO--Blog
 * @author maoge
 * @date 2020-01-29
 */
public class BlogDao {
	public NamedParameterJdbcTemplate getNamedTemplate() {
		return namedTemplate;
	}
	public void setNamedTemplate(NamedParameterJdbcTemplate namedTemplate) {
		this.namedTemplate = namedTemplate;
	}
	private NamedParameterJdbcTemplate namedTemplate;
	/**
	 * Newly added
	 */
	public void insert(BlogDo blog) {
		Map<String, Object> map = new HashMap<>();
		map.put("author", blog.getAuthor());
		map.put("content", blog.getContent());
		map.put("title", blog.getTitle());
		// Attention to use: xxx space
		namedTemplate.update("insert into blog(author,content,title)values(:author,:content,:title)", map);
	}
}

Third, write BlogService and call BlogDao type object to operate database. Note here that we added the annotation @ Transactional to the method addTwoBlog, which opens the transaction.

package org.maoge.transactionaldemo;
import org.springframework.transaction.annotation.Transactional;
public class BlogService {
	public BlogDao getBlogDao() {
		return blogDao;
	}
	public void setBlogDao(BlogDao blogDao) {
		this.blogDao = blogDao;
	}
	private BlogDao blogDao;
	@Transactional
	public void addTwoBlog() {
		BlogDo blog = new BlogDo();
		blog.setContent("test");
		blogDao.insert(blog);
		int a = 1 / 0;// An exception occurred, causing the transaction to roll back, so no row of data will be inserted
		blogDao.insert(blog);
	}
}

Fourth, activate declarative transactions by configuring classes and registering classes as components. The difference is that @ EnableTransactionManagement / / is added to activate declarative transactions based on annotations.

package org.maoge.transactionaldemo;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration // Indicates that this class is a Spring configuration class, and the configuration information of this class needs to be scanned
@EnableTransactionManagement // Activate annotation based declarative transactions
public class SpringConfig {
	/**
	 * Define data source bean s
	 */
	@Bean
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/myblog?useUnicode=true&characterEncoding=utf-8");
		dataSource.setUsername("root");
		dataSource.setPassword("Easy@0122");
		return dataSource;
	}

	/**
	 * Defining transaction management bean s
	 */
	@Bean
	public PlatformTransactionManager transactionManager() {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource());// Inject dataSource
		return transactionManager;
	}

	/**
	 * Define bean s of type TransactionTemplate
	 */
	@Bean
	public TransactionTemplate transactionTemplate() {
		TransactionTemplate transactionTemplate = new TransactionTemplate();
		transactionTemplate.setTransactionManager(transactionManager());// Inject transaction manager
		return transactionTemplate;
	}

	/**
	 * Configure the namedParameterJdbcTemplate component
	 */
	@Bean
	public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
		NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource());// Inject dataSource
		return template;
	}

	/**
	 * Register bean s for BlogDao
	 */
	@Bean
	public BlogDao blogDao() {
		BlogDao blogDao = new BlogDao();
		blogDao.setNamedTemplate(namedParameterJdbcTemplate());// Inject namedParameterJdbcTemplate
		return blogDao;
	}

	/**
	 * Register bean s for BlogService
	 */
	@Bean
	public BlogService blogService() {
		BlogService blogService = new BlogService();
		blogService.setBlogDao(blogDao());// Inject blogDao
		return blogService;
	}
}

Fifth, testing

package org.maoge.transactionaldemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
	public static void main(String[] args) {
		// Get container
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
		// Get database operation component in container
		BlogService blogService = (BlogService) context.getBean("blogService");
		blogService.addTwoBlog();
	}
}

When int a = 1 / 0; in addTwoBlog is executed, an exception occurs, causing the transaction to roll back, so no row of data will be inserted.

summary

The declarative annotation is too simple. First activate the annotation through @ EnableTransactionManagement, and then add @ Transactional to the method that needs to open the transaction.

This Component adopts the configuration mode of JavaConfig. In fact, for BlogDao and BlogService, you can register them as bean s by annotating @ Repository, @ Service or @ Component on the class. The effect is the same.

359 original articles published, 241 praised, 530000 visitors+
His message board follow

Posted by Hi I Am Timbo on Thu, 06 Feb 2020 01:37:05 -0800