16-Spring-声明式事务

starrylsi
2024-09-13 / 0 评论 / 14 阅读 / 正在检测是否收录...

**

遇到问题: jar包未构建,数据库驱动与版本不同,数据库默认引擎不是InooDB导致没有事务
收获: 编码要规范, 可以配合商家,骑手,客户三个之间的关系理解事物

需要了解Mybatis中DAO接口的工作原理

概念

事务分为声明式和编程式两种:

  • 声明式事务:声明式事务是指通过注解的形式对事务的各种特性进行控制和管理。
  • 编码式(编程式)事务:指的是通过编码的方式实现事务的声明。

1. 声明式事务环境搭建

1.1 准备测试数据库

##创建tx数据库
drop database if exists `tx`;
CREATE database `tx`;
##切换tx数据库
USE `tx`;

##删除用户表
DROP TABLE IF EXISTS `user`;
##创建用户表
CREATE TABLE `user` (
  `id` int primary key auto_increment,    
  `username` varchar(50) NOT NULL,
  `money` int(11) DEFAULT NULL
);
##插入数据
insert  into `user`(`username`,`money`) values ('张三',1000),('李四',1000);

##删除图书表
drop table if exists `book`;
##创建图书表
create table `book`(
    `id` int primary key auto_increment,
    `name` varchar(500) not null,
    `stock` int
);
##插入数据
insert into book(`name`,`stock`) values('java编程思想',100),('C++编程思想',100);

##查看数据
select * from book;
select * from user;

1.2 创建一个java工程,导入jar包

// 先导入AOP包,因为Spring的底层事务使用到了aop功能
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar

// 导入spring核心包,mybatis包,日志包等;
com.springsource.net.sf.cglib-2.2.0.jar
commons-logging-1.1.3.jar
druid-1.1.10.jar
log4j-1.2.17.jar
mybatis-3.4.1.jar
mybatis-spring-1.3.0.jar
mysql-connector-java-8.0.28.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-test-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar

1.3 Book,User,Service

  • top.starrylsi.pojo
    注意: 需要符合javaBean规范

    public class Book {
    
      private Integer id;
      private String name;
      private int stock;
    
    public class User {
    
      private Integer id;
      private String username;
      private int money;
    
  • DAO(数据访问对象层)
    关键: 只关注于下sql语句

    @Repository
    public class BookDao {
    
      @Autowired
      private JdbcTemplate jdbcTemplate;
    
      public int updateBook() {
          String sql = "update book set name = '**我被修改了!**' where id = 1";
          return jdbcTemplate.update(sql);
      }
    
    }
    
    @Repository
    public class UserDao {
    
      @Autowired
      private JdbcTemplate jdbcTemplate;
    
      public int updateUser() {
          String sql = "update user set username = '**我被修改了**' where id = 1";
          return jdbcTemplate.update(sql);
      }
    
    }
  • Service(业务逻辑层)
    关键: 引入DAO层,对数据进一步处理

    @Service
    public class TransactionService {
    
      @Autowired
      private UserDao userDao;
    
      @Autowired
      private BookDao bookDao;
    
      public void updateTwoTable() {
          userDao.updateUser();
          bookDao.updateBook();
      }
    
    }

1.4 创建并配置四个配置文件

config/
      db.properties
      mybatis-config.xml
      spring.xml
      log4j.properties
  • db.propertis

    db.driverClassName=com.mysql.cj.jdbc.Driver
    db.url=jdbc:mysql://localhost:3306/tx?rewriteBatchedStatements=true
    db.username=root
    db.password=123456
    initialSize=10
    minIdle=5
    maxActive=20
    maxWait=5000
  • mybatis-config
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- 按照驼峰命名匹配 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        
        <!-- 配置延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        
        <!-- 将积极加载配置成消极加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        
    </settings>
    
    <typeAliases>
        <package name="top.starrylsi.pojo"/>
    </typeAliases>
</configuration>
  • log4j.propertis
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • spring.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
      
      <!-- 扫描注解 排除spring-mvc的注解 -->
      <context:component-scan base-package="top.starrylsi">
          <context:exclude-filter type="annotation"
              expression="org.springframework.stereotype.Controller" />
      </context:component-scan>
      
      <!-- 加载jdbc配置文件 -->
      <context:property-placeholder location="classpath:jdbc.properties" />
      
      <!-- 创建数据库连接池 -->
      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
          <property name="driverClassName" value="${db.driverClassName}" />
          <property name="url" value="${db.url}" />
          <property name="username" value="${db.username}" />
          <property name="password" value="${db.password}" />
      </bean>
      
      
      <!-- 配置事务管理器 -->
      <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource" />
      </bean>
      
      <!-- 配置mybatis -->
      <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="configLocation" value="classpath:mybatis-config.xml" />
          <property name="mapperLocations" value="classpath:top/starrylsi/dao/*.xml" />
      </bean>
      
      <!-- 配置mybatis中使用的dao接口 -->
      <mybatis-spring:scan base-package="top.starrylsi.dao" />
    
       <!-- 配置spring事务 -->
       <tx:annotation-driven transaction-manager="transactionManager"/>
      
    </beans>
0

评论 (0)

取消