springboot2.x基础教程:springboot整合mybatis附源码(代码片段)

Java程序鱼 Java程序鱼     2023-01-09     175

关键词:

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


上篇文章我们介绍了 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 = '文章表';

二、添加依赖

<dependencies>
	
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
</dependencies>

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

三、配置数据源

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

修改

@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);

查询

@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);


删除

@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);

六、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 id="create" parameterType="com.fish.chapter6.domain.Blog">
    INSERT INTO article (title, author) VALUES (#title, #author)
</insert>

修改

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

<update id="updateById" parameterType="com.fish.chapter6.domain.Blog">
    UPDATE article SET title = #title, author = #author WHERE id = #id
</update>

查询

@Mapper
public interface BlogMapper 

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

<select id="getByTitle" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from article
        <where>
            <if test="title != null and title !=''">
                AND title = #title,jdbcType=VARCHAR
            </if>
        </where>
</select>

<select id="getAll" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from article
</select>

删除

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

<delete id="deleteById" parameterType="java.lang.Integer">
    DELETE FROM article WHERE id = #id
</delete>

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

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

七、源码

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

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

2018最新springboot2.0教程(零基础入门)

一、零基础快速入门SpringBoot2.01、SpringBoot2.x课程全套介绍和高手系列知识点简介:介绍SpringBoot2.x课程大纲章节java基础,jdk环境,maven基础2、SpringBoot2.x依赖环境和版本新特性说明简介:讲解新版本依赖环境和springboot2新特性概述3... 查看详情

springboot2.x基础教程:快速入门(代码片段)

如果文章对你有帮助,欢迎关注、点赞、收藏(一键三连)和订阅专栏微信号:hzy1014211086,如果你正在学习SpringBoot,可以加入我们的Spring技术交流群,共同成长序号内容1面试题专栏2Redis专栏3SpringBoot专栏3SpringBoo... 查看详情

springboot2.x基础教程:快速入门(代码片段)

简介在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用SpringBoot来让你更易上手,更简单快捷地构建Spring... 查看详情

springboot2.x基础教程:使用集中式缓存redis

之前我们介绍了两种进程内缓存的用法,包括SpringBoot默认使用的ConcurrentMap缓存以及缓存框架EhCache。虽然EhCache已经能够适用很多应用场景,但是由于EhCache是进程内的缓存框架,在集群模式下时,各应用服务器之间的缓存都是独... 查看详情

springboot2.x基础教程:使用springdatajpa访问mysql

在数据访问这章的第一篇文章《Spring中使用JdbcTemplate访问数据库》中,我们已经介绍了如何使用SpringBoot中最基本的jdbc模块来实现关系型数据库的数据读写操作。那么结合Web开发一章的内容,我们就可以利用JDBC模块与Web模块的功... 查看详情

springboot2.x基础教程:使用@scheduled实现定时任务(代码片段)

我们在编写SpringBoot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。创建定时任务在SpringBoot中编写定时任务是非常简单的事,... 查看详情

springboot2.x基础教程:使用jdbctemplate访问mysql数据库

在第2章节中,我们介绍了如何通过SpringBoot来实现HTTP接口,以及围绕HTTP接口相关的单元测试、文档生成等实用技能。但是,这些内容还不足以帮助我们构建一个动态应用的服务端程序。不论我们是要做App、小程序、还是传统的We... 查看详情

springboot2.x基础教程:springboot整合mybatis附源码(代码片段)

微信号:hzy1014211086,如果你正在学习SpringBoot,可以加入我们的Spring技术交流群,共同成长文章目录一、准备数据表二、添加依赖三、配置数据源四、编写领域对象五、注解配置方式新增修改查询删除六、XML配置... 查看详情

springboot2.x基础教程:使用elasticjob实现定时任务(代码片段)

上一篇,我们介绍了如何使用SpringBoot自带的@Scheduled注解实现定时任务。文末也提及了这种方式的局限性。当在集群环境下的时候,如果任务的执行或操作依赖一些共享资源的话,就会存在竞争关系。如果不引入分... 查看详情

零基础快速入门springboot2.0教程

一、SpringBoot2.x使用Dev-tool热部署简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用官方地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-devtools核心依赖包:<dependency 查看详情

springboot2.x最佳实践《一》之springboot2.x初体验

SpringBoot2.X最佳实践前言本系列文章,从零基础接触 SpringBoot2.x新版本,基础入门使用,热部署,到整合各个主流框架Redis4.x,消息队列AciveMQ,RocketMQ等,搜索框架ElasticSearch5.6版本,到web-flux反应式编程,到Actuator监控应用信息... 查看详情

springboot2.x基础教程:使用@scheduled实现定时任务(代码片段)

我们在编写SpringBoot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。创建定时任务在SpringBoot中编写定时任务是非常简单的事,... 查看详情

springboot2.x:入门篇(代码片段)

什么是SpringBootSpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架遵循”约定优于配置“的思想,清除了原先使用Spring框架的那些样板化的配置,继承了原有Spring框架的优... 查看详情

springboot2.x教程-thymeleaf原理是什么

layout:posttitle:SpringBoot2.x教程-Thymeleaf原理是什么categories:SpringBootdescription:SpringBoot2.x教程-Thymeleaf原理是什么keywords:SpringBoot,Spring,Thymeleaf---如要要理清楚Thymeleaf的原理,那么就要从模板引擎的原理说起。Thymeleaf只不过是众多模板 查看详情

springboot2.x系列教程48--多数据源配置之aop动态切换数据源

SpringBoot2.x系列教程48--多数据源配置之AOP动态切换数据源作者:一一哥在上一节中,我通过分包的方式实现了多数据源的配置,接下来我通过AOP切面的方式,带领大家实现第二种多数据源配置方式,该方式是在前面案例的基础上... 查看详情

springboot2.x系列教程48--多数据源配置之aop动态切换数据源

SpringBoot2.x系列教程48--多数据源配置之AOP动态切换数据源作者:一一哥在上一节中,我通过分包的方式实现了多数据源的配置,接下来我通过AOP切面的方式,带领大家实现第二种多数据源配置方式,该方式是在前面案例的基础上... 查看详情

springboot2.0图文教程|集成邮件发送功能

...springboot/spring-boots-send-mail大家好,后续会间断地奉上一些SpringBoot2.x相关的博文,包括SpringBoot2.x教程和SpringBoot2.x新特性教程相关,如WebFlux等。还有自定义Starter组件的进阶教程,比如:如何封装一个自定义图 查看详情

零基础快速入门springboot2.0

零基础快速入门SpringBoot2.0(一) 一、SpringBoot2.x依赖环境和版本新特性说明简介:讲解新版本依赖环境和springboot2新特性概述              1、依赖版本jdk8以上,Springboot2.x用JDK8 查看详情