SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】

微信号:hzy1014211086,如果你正在学习Spring Boot,可以加入我们的Spring技术交流群,共同成长

文章目录

  • 一、准备数据表
  • 二、添加依赖
  • 三、配置数据源
  • 四、编写领域对象
  • 五、注解配置方式
    • 新增
    • 修改
    • 查询
    • 删除
  • 六、XML配置方式
    • 新增
    • 修改
    • 查询
    • 删除
  • 七、源码


上篇文章我们介绍了 Spring Boot 对传统 JdbcTemplate 的集成,这篇文章我给大家介绍 Spring Boot 集成 MyBatis。这里分别介绍注解方式以及XML方式的整合。

一、准备数据表

CREATE TABLE `spring_boot`.`article`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NULL COMMENT '文章标题',
  `author` varchar(255) NULL COMMENT '作者',
  PRIMARY KEY (`id`)
) COMMENT = '文章表';

二、添加依赖


	
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.2.0
		
		
		
			mysql
			mysql-connector-java
			runtime
		

SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第1张图片

大家要注意依赖版本兼容性

三、配置数据源

spring.datasource.url = jdbc:mysql://139.196.20.xxx:3306/spring_boot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

四、编写领域对象

@Data
@NoArgsConstructor
public class Blog {
     
  private Integer id;
  private String title;
  private String author;
}

五、注解配置方式

新增

@RestController
public class BlogController {
     

  @Autowired
  public BlogService blogService;

  /**
   * 新增一篇文章
   *
   * @param blog 文章实体类
   * @return
   */
  @PostMapping(value = "/create")
  public Object create(@RequestBody Blog blog) {
     
    if (StringUtils.isBlank(blog.getTitle())) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
    }
    if (StringUtils.isBlank(blog.getAuthor())) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章作者");
    }
    return blogService.create(blog);
  }
}

@Service
public class BlogServiceImpl implements BlogService {
     

  @Autowired
  private BlogMapper blogMapper;

  @Override
  public Object create(Blog blog) {
     
    int count = blogMapper.create(blog);
    if (count > 0) {
     
      return ResponseUtil.ok("插入成功");
    } else {
     
      return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "插入失败");
    }
  }
}

@Mapper
public interface BlogMapper {
     
  @Insert("INSERT INTO article(title, author) VALUES(#{title}, #{author})")
  int create(Blog blog);
}

SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第2张图片

修改

@RestController
public class BlogController {
     

  @Autowired
  public BlogService blogService;

  /**
   * 通过id修改文章
   *
   * @param blog
   * @return
   */
  @PostMapping(value = "/updateById")
  public Object updateById(@RequestBody Blog blog) {
     
    if (StringUtils.isBlank(blog.getTitle())) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
    }
    if (StringUtils.isBlank(blog.getAuthor())) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章作者");
    }
    return blogService.updateById(blog);
  }
}

@Service
public class BlogServiceImpl implements BlogService {
     

  @Autowired
  private BlogMapper blogMapper;

  @Override
  public Object updateById(Blog blog) {
     
    int count = blogMapper.updateById(blog);
    if (count > 0) {
     
      return ResponseUtil.ok("修改成功");
    } else {
     
      return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "修改失败");
    }
  }
}

@Mapper
public interface BlogMapper {
     
  @Update("UPDATE article SET title=#{title},author=#{author} WHERE id=#{id}")
  int updateById(Blog blog);
}

SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第3张图片

查询

@RestController
public class BlogController {
     

  @Autowired
  public BlogService blogService;

  /**
   * 查询所有文章
   *
   * @return
   */
  @GetMapping(value = "/getAll")
  public List<Blog> getAll() {
     
    return blogService.getAll();
  }


  /**
   * 通过标题查询文章
   *
   * @param title
   * @return
   */
  @GetMapping(value = "/getByTitle")
  public Object getByTitle(String title) {
     
    if (StringUtils.isBlank(title)) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
    }
    return blogService.getByTitle(title);
  }
}

@Service
public class BlogServiceImpl implements BlogService {
     

  @Autowired
  private BlogMapper blogMapper;

  @Override
  public List<Blog> getAll() {
     
    return blogMapper.getAll();
  }


  @Override
  public List<Blog> getByTitle(String title) {
     
    return blogMapper.getByTitle(title);
  }
}

@Mapper
public interface BlogMapper {
     

  @Select("SELECT * FROM article")
  @Results({
     
    @Result(column = "id", property = "id", javaType = Integer.class),
    @Result(property = "title", column = "title", javaType = String.class),
    @Result(property = "author", column = "author", javaType = String.class)
  })
  List<Blog> getAll();

  @Select("SELECT * FROM article WHERE title = #{title}")
  @Results({
     
    @Result(column = "id", property = "id", javaType = Integer.class),
    @Result(property = "title", column = "title", javaType = String.class),
    @Result(property = "author", column = "author", javaType = String.class)
  })
  List<Blog> getByTitle(String title);
}

SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第4张图片
SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第5张图片

删除

@RestController
public class BlogController {
     

  @Autowired
  public BlogService blogService;

  /**
   * 通过ID删除文章
   *
   * @param id
   * @return
   */
  @PostMapping(value = "/deleteById")
  public Object deleteById(Integer id) {
     
    if (null == id || 0 == id.longValue()) {
     
      return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章id");
    }
    return blogService.deleteById(id);
  }
}

@Service
public class BlogServiceImpl implements BlogService {
     

  @Autowired
  private BlogMapper blogMapper;
  
  @Override
  public Object deleteById(Integer id) {
     
    int count = blogMapper.deleteById(id);
    if (count > 0) {
     
      return ResponseUtil.ok("删除成功");
    } else {
     
      return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "删除失败");
    }
  }
}

@Mapper
public interface BlogMapper {
     
  @Delete("DELETE FROM article WHERE id = #{id}")
  int deleteById(Integer id);
}

SpringBoot2.X基础教程:SpringBoot整合MyBatis【附源码】_第6张图片

六、XML配置方式

修改application.properties 配置文件

#指定bean所在包
mybatis.type-aliases-package=com.fish.chapter6.domain
#指定映射文件
mybatis.mapperLocations=classpath:mapper/*.xml

新增

@Mapper
public interface BlogMapper {
     
  int create(Blog blog);
}

    INSERT INTO article (title, author) VALUES (#{title}, #{author})

修改

@Mapper
public interface BlogMapper {
     
  int updateById(Blog blog);
}

    UPDATE article SET title = #{title}, author = #{author} WHERE id = #{id}

查询

@Mapper
public interface BlogMapper {
     

  List<Blog> getAll();
  
  List<Blog> getByTitle(@Param("title") String title);
  
}



删除

@Mapper
public interface BlogMapper {
     
  int deleteById(@Param("id") Integer id);
}

    DELETE FROM article WHERE id = #{id}

更多mybatis数据访问操作的使用请参考:MyBatis官方中文参考文档

彩蛋,很多小伙伴会发现一个问题,项目启动一段时间放那里不动,然后在访问接口时,就会报错,这和我们使用的数据源有关(Hikari),在后面《数据源详解》章节我会教大家如何解决。

七、源码

本文的相关例子可以查看下面仓库中的 chapter6 目录:

  • Gitee:https://gitee.com/hezhiyuan007/spring-boot-study
  • Github:https://github.com/java-fish-0907/spring-boot-study

你可能感兴趣的:(SpringBoot专栏,spring,boot,spring)