MyBatis-plus配置和测试微服务基本CRUD

眉间皱痕 提交于 2020-10-16 08:43:17

一 整合MyBatis-Plus

1 导入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>

2 配置

2.1 配置数据源

a 导入数据库的驱动。

<!--    导入mysql驱动    -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

版本对应关系:https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-versions.html

b 在application.yml配置数据源相关信息

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.110:3306/gulimall_pms
    driver-class-name: com.mysql.jdbc.Driver

2.2 配置MyBatis-Plus

a 使用@MapperScan、

@MapperScan("com.atguigu.gulimall.product.dao")
@SpringBootApplication
public class GulimallProductApplication {
    public static void main(String[] args) {
        SpringApplication.run(GulimallProductApplication.class, args);
    }
}

b 告诉MyBatis-Plus,sql映射文件位置,以及主键自增策略

mybatis-plus:
  mapper-locations: classpath:/mapper/**/*.xml
  global-config:
    db-config:
      id-type: auto
      logic-delete-value: 1
      logic-not-delete-value: 0

二 单元测试

1 测试新增

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallProductApplicationTests {
    @Autowired
    BrandService brandService;

    @Test
    public void contextLoads() {

        BrandEntity brandEntity = new BrandEntity();
        brandEntity.setName("华为");
        brandService.save(brandEntity);
        System.out.println("保存成功....");
    }
}

2 测试结果

3 测试修改

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallProductApplicationTests {
    @Autowired
    BrandService brandService;

    @Test
    public void contextLoads() {
        BrandEntity brandEntity = new BrandEntity();
        brandEntity.setBrandId(1L);
        brandEntity.setDescript("华为");
        brandService.updateById(brandEntity);
    }
}

4 测试结果

5 测试查询

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallProductApplicationTests {
    @Autowired
    BrandService brandService;

    @Test
    public void contextLoads() {

        List<BrandEntity> list = brandService.list(new QueryWrapper<BrandEntity>().eq("brand_id", 1L));
        list.forEach((item) -> {
            System.out.println(item);
        });
    }
}

6 测试结果

BrandEntity(brandId=1, name=华为, logo=null, descript=华为, showStatus=null, firstLetter=null, sort=null)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!