SpringBoot 系列教程 Mybatis+注解整合篇

SpringBoot 系列教程 Mybatis+注解整合篇_第1张图片

SpringBoot 系列教程 Mybatis+注解整合篇

上一篇博文介绍了 SpringBoot 整合 mybatis 的过程,但是 xml 的方式,总感觉让人有点蛋疼;本文将介绍一种 noxml 的使用姿势,纯用注解的方式来支持 CURD

I. 环境

本文使用 SpringBoot 版本为 2.2.1.RELEASE, mybatis 版本为1.3.2,数据库为 mysql 5+

1. 项目搭建

推荐是用官方的教程来创建一个 SpringBoot 项目; 如果直接创建一个 maven 工程的话,将下面配置内容,拷贝到你的pom.xml

  • 主要引入的是mybatis-spring-boot-starter,可以减少令人窒息的配置

    org.springframework.boot
    spring-boot-starter-parent
    2.2.1.RELEASE
     



    UTF-8
    UTF-8
    1.8



    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.2
    
    
        mysql
        mysql-connector-java
    



    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


    
        spring-snapshots
        Spring Snapshots
        https://repo.spring.io/libs-snapshot-local
        
            true
        
    
    
        spring-milestones
        Spring Milestones
        https://repo.spring.io/libs-milestone-local
        
            false
        
    
    
        spring-releases
        Spring Releases
        https://repo.spring.io/libs-release-local
        
            false
        
    

2. 配置信息

application.yml 配置文件中,加一下 db 的相关配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password:

接下来准备一个测试表(依然借用之前 db 操作系列博文中的表结构),用于后续的 CURD;表结果信息如下

DROP TABLE IF EXISTS `money`;

CREATE TABLE `money` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
  `money` int(26) NOT NULL DEFAULT '0' COMMENT '有多少钱',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

II. 实例整合

在前一篇的基础上进行扩展,重点在于干掉了 xml 文件,在 DAO 接口上通过注解来实现 CURD

1. PO

创建表对应的 PO 对象: MoneyPo

@Data
public class MoneyPo {
    private Integer id;

    private String name;

    private Long money;

    private Integer isDeleted;

    private Timestamp createAt;

    private Timestamp updateAt;
}

2. DAO 接口

表的操作接口,下面简单的写了四个接口,分别对应 CRUID 四种操作

@Mapper
public interface MoneyMapper {

    // 支持主键写回到po

    @Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
    @Insert("insert into money (name, money, is_deleted) values (#{po.name}, #{po.money}, #{po.isDeleted})")
    int savePo(@Param("po") MoneyPo po);

    @Select("select * from money where name=#{name}")
    @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
            @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER),
            @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT),
            @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP),
            @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)})
    List findByName(@Param("name") String name);

    @Update("update money set money=money+#{money} where id=#{id}")
    int addMoney(@Param("id") int id, @Param("money") int money);

    @Delete("delete from money where id = #{id,jdbcType=INTEGER}")
    int delPo(@Param("id") int id);

    @Select("")
    @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER),
                @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
                @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER),
                @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT),
                @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP),
                @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)})
    List findByPo(MoneyPo po);
}

从 mapper 的实现上,也可以看出来,通过 @Insert, @Select, @Update, @Delete 四个注解来实现 CURD,使用上面这种方式时,有几个点需要注意

  • insert: 当我们希望插入的主键写回到 PO 时,可以配置@Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
  • 动态 sql: 在注解中,通过

你可能感兴趣的:(SpringBoot 系列教程 Mybatis+注解整合篇)