Spring声明式事务

148 阅读1分钟

Srping声明式事务的使用

环境搭建:导入数据源、数据库驱动、Spring-jdbc依赖在pom.xml新增c3p0依赖包(c3p0封装了jdbc 对DataSource接口的实现)

<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.44</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>

创建配置类

@Configuration
@ComponentScan("com.enjoy.cap11")
public class MainConfig {

    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException {
        return new DataSourceTransactionManager(dataSource());
    }
}

新建一个OrderDao

@Repository
public class OrderDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //操作数据的方法
    public void insert() {
        String sql = "insert into `order` (ordertime, ordermoney, orderstatus) values(?,?,?)";
        jdbcTemplate.update(sql, new Date(), 20, 0);
    }
}

新建一个OrdderService

@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;

    @Transactional
    public void addOrder() {
        orderDao.insert();
        System.out.println("操作完成.........");

        //int a = 1/0; 
    }
}

源码分析:

照旧,贴图

Transaction