SpringBoot中整合Mybatis及使用

继上一篇文章我们讲了SpringBoot 整合 JdbcTemplate之后,这篇文章我们来讲一讲SpringBoot中另外一个持久化框架:MyBatis。MyBatis在Spring + SpringMVC中使用还是比较复杂,需要开发人员手动配置SqlSessionFactoryBean 与MapperScannerConfigurer,但是在SpringBoot中,因为MybatisAutoConfiguration 类的存在,MyBatis在SpringBoot中可以做到开箱即用,下面我们就来看看具体是如何使用的。

1. 配置

  1. pom.xml配置
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid-spring-boot-starter</artifactId>
       <version>1.1.10</version>
    </dependency>
    
    <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>2.0.0</version>
    </dependency>
    <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.27</version>
       <scope>runtime</scope>
    </dependency>
    
  2. application.properties配置
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.username=root
    spring.datasource.password=qwe123
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/train?useUnicode=true&characterEncoding=UTF-8
    
  3. IDEA配置
    因为在IDEA中,默认扫描显示配置的Bean,而Mapper使用@Mapper配置,并不能被扫描到,所以我们使用@Autowired userMapper时会出现:Could not autowire. No beans of ‘UserMapper’ type found. 的错误提示。在这里插入图片描述所以我们需要将IDEA默认ERROR提示改为WARNING。
    在这里插入图片描述
    这样就不会再有错误提示了。
  4. 数据库配置,创建User表
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `id` bigint(255) NOT NULL AUTO_INCREMENT,
      `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `address` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    并创建对应的User实体类
    @Data //生成getter,setter等函数
    @AllArgsConstructor //生成全参数构造函数
    @NoArgsConstructor //生成无参构造函数
    @ApiModel//在swagger中说明当前实体
    public class User {
        @ApiModelProperty(value = "用户id")
        private Long id;
    
        @ApiModelProperty(value = "用户名")
        private String name;
    
        @ApiModelProperty(value = "用户地址")
        private String address;
    }
    

2. MyBatis轻使用

  1. 我们先创建Mapper接口
    @Mapper
    public interface UserMapper {
        @Select("select * from user")
        List<User> getAllUsers();
    
        @Results({
                @Result(property = "id", column = "id"),
                @Result(property = "name", column = "u"),
                @Result(property = "address", column = "a")
        })
        @Select("select name as u,address as a,id as id from user where id=#{id}")
        User getUserById(Long id);
    
        @Select("select * from user where name like concat('%',#{name},'%')")
        List<User> getUsersByName(String name);
    
        //@SelectKey 注解可以实现主键回填的功能,即当数据插入成功后,插入成功的数据 id 会赋值到 user 对象的id 属性上。
        @Insert({"insert into user(name,address) values(#{name},#{address})"})
        @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Long.class, statementType = StatementType.PREPARED)
        Long addUser(User user);
    
        @Update("update user set name=#{name},address=#{address} where id=#{id}")
        Integer updateUserById(User user);
    
        @Delete("delete from user where id=#{id}")
        Integer deleteUserById(Integer id);
    }
    
  2. 因为只是测试,所以我们这里就不再创建Service层,直接创建Controller层
    @RestController
    @Api(tags = "用户管理接口_MyBatis")
    @RequestMapping("/userMp")
    public class UserMpController {
    
        @Autowired
        UserMapper userMapper;
    
        @GetMapping("/")
        @ApiOperation("查询所有用户")
        public List<User> getAllUsers(){
            return userMapper.getAllUsers();
        }
    
        @GetMapping("/{id}")
        @ApiOperation("根据ID查询用户")
        @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "1")
        public User getUserById(@PathVariable Long id){
            return userMapper.getUserById(id);
        }
    
        @PostMapping("/")
        @ApiOperation("添加用户")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "name", value = "用户名", defaultValue = "李四"),
                @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳")
        })
        public Long addUser(User user){
            Long aLong = userMapper.addUser(user);
            System.out.println(user.toString());
            return aLong;
        }
    }
    
    这里我们创建的是标准的RESTFUL接口,并且使用Swagger注解每个接口的使用说明。所以我们可以直接在Swagger中进行测试。
    1. 查询所有用户
      在这里插入图片描述
    2. 根据ID查询一个用户
      在这里插入图片描述
    3. 新增用户
      在这里插入图片描述
      其他的修改删除等用法,各位小伙伴可以在文末的GitHub连接中下载代码进行测试。

3. 说说@SelectKey 注解

在MyBatis中,当我们将MySQL数据表的主键设置为自增主键时,可以使用@SelectKey返回最新插入的id;

@SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Long.class, statementType = StatementType.PREPARED)
属性描述
statementselect last_insert_id(),查询数据库最新插入的ID
keyPropertyselectKey 语句结果应该被设置的目标属性
resultType结果的类型。MyBatis 通常可以算出来,但是写上也没有问题。MyBatis 允许任何简单类型用作主键的类型,包括字符串
before值为true是,在插入之前查询,值为false则在插入之后查询,这里必须设置为false
statementType和前面的相 同,MyBatis 支持 STATEMENT ,PREPARED 和CALLABLE 语句的映射类型,分别代表 PreparedStatement 和CallableStatement 类型

4. 总结

MyBatis在SpringBoot中做到了开箱即用,还是比较简单的,当然还有更多的复杂用法,后续也会出教程文章,请关注哦。

项目已上传至github,项目源码地址

https://github.com/kenyonlover/springboot2train.git
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值