Bootstrap

PassJava 开源 (四):整合MyBatis-Plus实现CRUD

作者简介:悟空,8年一线互联网开发和架构经验,用故事讲解分布式、架构设计、Java 核心技术。《JVM性能优化实战》专栏作者,开源了《Spring Cloud 实战 PassJava》项目,公众号:。本文已收录至 

PassJava (佳必过) 项目全套学习教程连载中,关注公众号第一时间获取。

文档在线地址:www.passjava.cn

整合MyBatis-Plus实现CRUD

1.添加Mybatis-Plus依赖


    com.baomidou
    mybatis-plus-boot-starter
    3.2.0

2.配置数据源

  • 导入数据库的驱动

  • 查看mysql版本 5.7.29

到maven仓库查看适用的mysql驱动,5.7的没有,8.0兼容5.7的,所以选择8.0的驱动



    mysql
    mysql-connector-java
    8.0.17

3.配置MyBatis-Plus

  • 添加application.yml 文件配置数据源

  • 文件路径:/passjava-question/src/main/resources/application.yml

  spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://129.211.188.xxx:3306/passjava_admin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
        username: root
        password: xxx

  • 配置mapper映射文件路径

  mybatis-plus:
    mapper-locations: classpath:/mapper/**/*.xml
    global-config:
      db-config:
        id-type: auto

  • 添加MapperScan注解

  @MapperScan("com.jackson0714.passjava.question.dao")
  @SpringBootApplication
  public class PassjavaQuestionApplication {
      public static void main(String[] args) {
          SpringApplication.run(PassjavaQuestionApplication.class, args);
      }
  }

4.测试mybatis-plus的CRUD方法

  • 创建类型为javaBasic的type表数据

  @Autowired
  TypeService typeService;
  
  // 创建题目类型
  @Test
  void testCreateType() {
      TypeEntity typeEntity = new TypeEntity();
      typeEntity.setType("javaBasic");
      typeService.save(typeEntity);
      System.out.println("创建成功");
  }

  • 更新id=1的表数据

  // 更新type=jvm
  @Test
  void testUpdateType() {
      TypeEntity typeEntity = new TypeEntity();
      typeEntity.setId(1L);
      typeEntity.setType("jvm");
      typeService.updateById(typeEntity);
      System.out.println("修改成功");
  }

  • 查询id=1的表数据

  // 查询题目类型
  @Test
  void testSelectType() {
      List typeEntityList = typeService.list(new QueryWrapper().eq("id",1L));
      typeEntityList.forEach((item)-> {
          System.out.println(item);
      });
      System.out.println("查询成功");
  }

  • 删除id=1的表数据

  // 删除题目类型记录
  @Test
  void testRemoveType() {
      typeService.removeById(1L);
      System.out.println("删除成功");
  }