Spring如何基于注解进行事务管理呢?

书欣 Spring 发布时间:2023-01-08 17:54:00 阅读数:18209 1
下文笔者讲述Spring中使用注解进行事务配置的方法分享,如下所示
实现思路:
    在Driud上使用注解
    @EnableTransactionManagement 
	即可开启事务

	具体的方法上加入@Transactional
	即可开启事务注解
例:
Spring项目中开启事务的示例分享
spring项目结构
数据库表结构
数据表结构

Maven导入事务控制及Spring的依赖

<dependencies>
    <!--spring上下文-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!--简化jdbc、事务控制-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!--测试-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!--aop依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!--druid连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.8</version>
    </dependency>

    <!--mysql连接-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
</dependencies>

实体类

package com.java265.pojo;

public class User {
    private Integer id;
    private String name;

    public User() {
    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

持久层

UserDao源码
package com.java265.dao;
import com.java265.pojo.User;
 
public interface UserDao {
    void insert(User user);
}

UserDaoImpl

package com.java265.dao.impl;

import com.java265.dao.UserDao;
import com.java265.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
 
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public void insert(User user) {
        String sql = "INSERT INTO t_test(`name`) VALUES(?)";
        jdbcTemplate.update(sql,user.getName());
    }
}

服务层

package com.java265.service;

import com.java265.dao.UserDao;
import com.java265.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public void insert(User user) {
        userDao.insert(user);
    }
}

连接池配置

druid.username=root
druid.password=123456
druid.url=jdbc:mysql://localhost:3306/test?useSSL=true
druid.driver=com.mysql.jdbc.Driver

注解核心配置

 
package com.java265;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan //同包下默认扫描
@EnableTransactionManagement //开启事务
@PropertySource("classpath:/druid.properties") //引入外部配置
public class TXConfig {
    @Value("${druid.driver}")
    private String driver;
    @Value("${druid.url}")
    private String url;
    @Value("${druid.username}")
    private String username;
    @Value("${druid.password}")
    private String password;

    /**
     * 配置数据源
     * @return 数据源
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 获取spring的jdbc模板(简化jdbc操作)
     * @param dataSource 自动装配数据源
     * @return jdbc模板
     */
    @Bean
    public JdbcTemplate jdbcTemplate (DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 事务管理器
     * @param dataSource 数据源
     * @return 平台事务管理器
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

测试类配置

package com.java265.test;

import com.java265.TXConfig;
import com.java265.pojo.User;
import com.java265.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TXConfig.class)
public class TxTest {
    @Autowired
    private UserService userService;
    @Test
    public void testInsert() {
        User user = new User();
        user.setName("admin");
        userService.insert(user);
    }
}
事务测试
  1.没有出现错误的情况下运行,成功向数据库中添加数据

  2.手动添加错误配置int i = 10 / 0

	@Transactional
	public void insert(User user) {
		String sql = "INSERT INTO t_test(`name`) VALUES(?)";
		jdbcTemplate.update(sql,user.getName());
		int i = 10 / 0;
	}
	可发现数据没有成功插入到数据库中
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202301/5314.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者