1、引入依赖

<?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.zwhxpp</groupId>
    <artifactId>springboot_anno_tx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!-- SpringBoot 容器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- SpringBoot集成通用Mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*Mapper.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

SpringBoot要求,所有的springboot工程要继承SpringBoot的起步依赖spring-boot-starter-parent

SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web功能的启动依赖

使用通用Mapper,需要两个依赖:mapper-spring-boot-starter和mysql-connector-java

注意:在使用IDEA开发时,如果打包时*Mapper.xml没有自动复制到class输出目录的mapper类包下,则需要在pom文件中添加mybatis加载配置文件的配置!如下:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*Mapper.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

否则报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

2、编写启动类

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

3、编写配置文件application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/eesy?characterEncoding=utf8&useoldAliasMetadataBehavior=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapperLocations = classpath*:com/zwhxpp/dao/mappers/*Mapper.xml
mybatis.typeAliasesPackage = com.zwhxpp.domain

注意:要指定mapper映射文件的位置,否则报错org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.zwhxpp.dao.AccountMapper.findAccountByName

4、编写实体类

@Table(name = "account1")
public class Account implements Serializable {
    @Id
    @KeySql(useGeneratedKeys = true)//开启主键自动回填
    private Integer id;
    private String name;
    private Float money;

    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;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

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

由于是直接与数据库交互,所以要用到Common Mapper中的注解:@Table、@Id、@KeySQL,注意要指定表名,否则不知道要操作哪张表。

5、编写controller

@Controller
public class AccountController {
    @Autowired
    private IAccountService accountService;
    @GetMapping("/test")
    public String test() {
        accountService.transfer("aaa","bbb",100f);
        return "OK";
    }
}

6、编写service接口

public interface IAccountService {
    /**
     * 转账
     * @param sourceName    转成账户名称
     * @param targetName    转入账户名称
     * @param money         转账金额
     */
    void transfer(String sourceName, String targetName, Float money);
}

7、编写service实现类

@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private AccountMapper accountMapper;
    //需要的是读写型事务配置
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1根据名称查询转出账户
        Account source = accountMapper.findAccountByName(sourceName);
        //2.2根据名称查询转入账户
        Account target = accountMapper.findAccountByName(targetName);
        //2.3转出账户减钱
        source.setMoney(source.getMoney()-money);
        //2.4转入账户加钱
        target.setMoney(target.getMoney()+money);
        //2.5更新转出账户
        accountMapper.updateByPrimaryKey(source);

//            int i=1/0;

        //2.6更新转入账户
        accountMapper.updateByPrimaryKey(target);
    }

}

8、编写dao接口

@org.apache.ibatis.annotations.Mapper
public interface AccountMapper extends Mapper<Account> {
    /**
     * 根据名称查询账户
     * @param accountName
     * @return
     */
    Account findAccountByName(@Param(value = "accountName") String accountName);

}

如果在启动类使用了@MapperScan注解,那么这里不用使用@Mapper注解

9、编写AccountMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zwhxpp.dao.AccountMapper">
    <select id="findAccountByName" parameterType="java.lang.String" resultType="com.zwhxpp.domain.Account">
        SELECT
        id,name,money
        FROM account1
        WHERE 1=1
        <if test="accountName != null">
            AND name = #{accountName}
        </if>
    </select>
</mapper>

10、创建数据库eesy下的account1表

 11、访问http://localhost:8080/test

结果如下:

 发现转账操作实现了事务控制。

 

posted on 2021-04-11 14:45  周文豪  阅读(939)  评论(0编辑  收藏  举报