MybatisPlus学习

介绍:MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 

小dome快速入门

实现获取所有  注:连接数据库,实体类记得自己写。用简单springboot项目改

依赖:

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

Mapper继承MybatisPlus提供的BaseMapper接口

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

测试获取所有User

@SpringBootTest
class MybatisPlusDomeApplicationTests {


    @Autowired
    UserMapper userMapper;

    @Test
    void testSelectList() {
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

}

测试结果

总结:

1.引入mybatisplus依赖

2.定义Mapper接口并继承BaseMapper<T>  范型为操作实体类类型

常用注解

MybatisPlus通过扫描实体类,并基于反射获取实体类信息作为数据库表信息。

  • 类名驼峰转下划线作为表名
  • 名为id的字段为主键
  • 变量名驼峰转下划线作为表的字段名

若实体类与数据库表不一致,用注解

  • @TableName:指定表名
  • @TableId:指定主键
  • @TableField:指定普通字段

@TableId(value="id" type= ? )  IdType.枚举

  • AUTO:id自增
  • INPUT:set方法自行输入
  • ASSIGN_ID:分配id,雪花算法

@TableField

成员变量名与数据库字段名不一致

成员变量名is开头,且是布尔值。MP自动去掉is后面的为字段名。

成员变量名与数据库关键字冲突

成员变量名不是数据库字段,处理@TableField(exist = false )

常见配置

mybatis-plus:
  mapper-locations: classpath*:mapper/**/*.xml #扫描xml文件路径 默认值
  type-aliases-package: com.xxzygx.pojo        #别名扫描包
  configuration:
    map-underscore-to-camel-case: true #开启驼峰命名
    cache-enabled: false #关闭缓存
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: assign_id #id生成雪花算法
      update-strategy: not_null #更新策略 只更新为空的字段

条件构造器

案例演示:

QueryWrapper、LambdaQueryWrapper(推荐使用)

1.查询菜品,价格大于10000

    @Test
    void testSelectList() {
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<Dish>().
                select("id", "name", "price").
                ge("price", 10000);
        List<Dish> users = dishMapper.selectList(dishQueryWrapper);
    }
    @Test
    void testSelectList() {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<Dish>().
                select(Dish::getId, Dish::getName, Dish::getPrice).
                ge(Dish::getPrice, 10000);
        List<Dish> users = dishMapper.selectList(dishQueryWrapper);
    }

查询结果

UpdateWrapper、LambdaUpdateWrapper(推荐使用)

2.修改名字为“米饭”的菜品价格为“11111.1111”

    @Test
    void testUpdate() {
        BigDecimal b2 = new BigDecimal("11111.1111");
        Dish dish = new Dish();
        dish.setPrice(b2);
        UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<Dish>().eq("name", "米饭");
        int update = dishMapper.update(dish,updateWrapper);
        log.info("update result: {}", update);
    }
    @Test
    void testUpdate() {
        BigDecimal b2 = new BigDecimal("11111.1111");
        Dish dish = new Dish();
        dish.setPrice(b2);
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<Dish>().eq(Dish::getName, "米饭");
        int update = dishMapper.update(dish,updateWrapper);
        log.info("update result: {}", update);
    }

测试结果

自定义SQL

3.查询name字段分类获取name,数据条数count,价格大于10000

利用MP的Wrapper来构建复杂的where条件,然后自己定义SQL语句的剩下部分。

  1. 基于Wrapper构建where条件
  2. 在mapper方法中用Param注解声明wrapper变量名称,必须是ew
  3. 自定义SQL,并使用Wrapper条件

逻辑层传入LambdaQueryWrapper

    @Test
    void getNameCountBypriceTest() {

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Dish::getPrice, 10000);
        List<DishVO> nameCountByprice = dishMapper.getNameCountByprice(queryWrapper);
        nameCountByprice.forEach(item -> {
            log.info("name: {}, count: {}", item.getName(), item.getCount());
        });
    }

DishMapper  @Param("ew") LambdaQueryWrapper<Dish> queryWrapper接收

   List<DishVO> getNameCountByprice(@Param("ew") LambdaQueryWrapper<Dish> queryWrapper);

DishMapper.xml ${ew.customSqlSegment}拼接where条件

    <select id="getNameCountByprice" resultType="com.sqy.pojo.DishVO">
        select name,count("id") as count from dish ${ew.customSqlSegment} GROUP BY name
    </select>

IService

IService基础实现

创建service包,创建service接口和实现serviceImpl类。service继承IService<T> 范型为与连接数据库表的实体类pojo。serviceImpl继承ServiceImpl<T,T>,2个范型分别为Mapper,实体类pojo。

例:

public interface DishService extends IService<Dish> {

}
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


}

测试

@SpringBootTest
class DishServiceImplTest {

    @Autowired
    DishService dishService;

    @Test
    void Test() {
        List<Dish> list = dishService.list();
        list.forEach(System.out::println);
    }

}

结果:

引入knife4j,方便接口测试

可以使用 knife4j-openapi2-spring-boot-starter,maven 坐标如下:

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

配置yml属性,如下:

knife4j:
  enable: true
  openapi:
    title: Knife4j官方文档
    description: "`我是测试`,**你知道吗** #标题
    # aaa"
    email: xiaoymin@foxmail.com
    concat: 八一菜刀  #作者
    url: https://docs.xiaominfo.com
    version: v4.0
    license: Apache 2.0
    license-url: https://stackoverflow.com/
    terms-of-service-url: https://stackoverflow.com/
    group:
      test1:
        group-name: 分组名称
        api-rule: package
        api-rule-resources:
          - com.knife4j.demo.new3 #controller路径

IService的Lambda查询

name:菜品关键字,可以为空

minPrice:最小金额,可以为空

maxPrice:最大金额,可以为空

DishController

@RestController
@Api(tags = "菜品管理")
public class DishController {

    @Autowired
    DishService dishService;


    @GetMapping("/dish/list")
    @ApiOperation(value = "条件获取菜品列表")
    public List<Dish> getDishListBy(DishQuery query) {
        List<Dish> list=  dishService.queryDishList(query.getName(),query.getMaxPrice(),query.getMinPrice());
        return list;
    }

}

DishService

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Override
    public List<Dish> queryDishList(String name, Double maxPrice,  Double minPrice) {
        List<Dish> list = lambdaQuery()
                .like(name != null, Dish::getName, name)

                .ge(minPrice != null, Dish::getPrice, minPrice)
                .le(maxPrice != null, Dish::getPrice, maxPrice)
                .list();
        return list;
    }
}

查询结果

MP插件

分页插件

使用分页插件需要配置MybatisPlusInterceptor,将分页拦截器添加进来:

@Configuration
public class MyBatisPlusConfig {

    /**
     * 分页插件配置
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 向MyBatis-Plus的过滤器链中添加分页拦截器,需要设置数据库类型(主要用于分页方言)
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

分页查询 按价格降序排序

controller

    @GetMapping("/dish/page")
    @ApiOperation(value = "分页查询")
    public Page<Dish> getDishListPage() {


        Page<Dish> dishPage = Page.of(1, 2);
        dishPage.addOrder(OrderItem.desc("price"));
        Page<Dish> page = dishService.page(dishPage);

        return page;
    }

调试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值