MyBatisPlus

目录

引入MybatisPlus的起步依赖

1、引入MybatisPlus依赖,代替Mybatis依赖

2.定义Mapper

常见注解

@TableName:用来指定表名

@Tableld:用来指定表中的主键字段信息

@TableField:用来指定表中的普通字段信息 

使用@TableField的常见场景:

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

​编辑

成员变量名以is开头,且是布尔值 

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

成员变量不是数据库字段 

常用配置 

条件构造器

基于QueryWrapper的查询

查询出名字中带o的,存款大于等于888元的人的id、username、info、balance字段

更新用户名为jack的用户的余额为1888 

基于UpdateWrapper的更新

自定义SQL

Service接口

 IService的Lambda查询

IService的Lambda更新

批处理方案

代码生成器



引入MybatisPlus的起步依赖

MyBatisPlus官方提供了starter,其中集成了Mybatis和MybatisPlus的所有功能,并且实现了自动装配效果。

1、引入MybatisPlus依赖,代替Mybatis依赖

因此我们可以用MybatisPlus的starter代替Mybatis的starter:

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

2.定义Mapper

自定义的Mapper继承MybatisPlus提供的BaseMapper接口:

public interface UserMapper extends BaseMapper<User>{

这个泛型是我们要操作的实体类的

可以看到没有写任何代码,也是可以操作数据库的

常见注解

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

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

MybatisPlus中比较常用的几个注解如下:

@TableName:用来指定表名

假如这个表名叫sys_user

实体类是User

就这样使用

@Tableld:用来指定表中的主键字段信息

IdType枚举:

  • AUTO:数据库自增长
  • INPUT:通过set方法自行输入
  • ASSIGN ID:分配lD,接口ldentifierGenerator的方法nextld来生成id默认实现类为DefaultldentifierGenerator雪花算法

@TableField:用来指定表中的普通字段信息 

使用@TableField的常见场景:

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

成员变量名以is开头,且是布尔值 

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

成员变量不是数据库字段 

常用配置 

条件构造器

MyBatisPlus支持各种复杂的where条件,可以满足日常开发的所有需求

基于QueryWrapper的查询

查询出名字中带o的,存款大于等于888元的人的id、username、info、balance字段

 

 

更新用户名为jack的用户的余额为1888 

基于UpdateWrapper的更新

更新id为1,2,4的用户的余额,扣200 

 

尽量使用LambdaQueryWrapper和LambdaUpdateWrapper,避免硬编码

QueryWrapper和LambdaQueryWrapper通常用来构建selectdelete、update的where条件部分

UpdateWrapper和LambdaUpdateWrapper通常只有在set语句比较特殊才使用 

自定义SQL

我们可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,然后自己定义SQL语句中剩下的部分。 

1、基于Wrapper构建where条件

2、在mapper方法参数中用Param注解声明wrapper变量名称,必须是ew

3、自定义SQL,并使用Wrapper条件

Service接口

自定义Service接口继承IService接口 

自定义Service实现类,实现自定义接口并继承Servicelmpl类

 例子:

controller层:

package com.yjj.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yjj.mp.domain.dto.UserFormDTO;
import com.yjj.mp.domain.po.User;
import com.yjj.mp.service.MyUserService;
import com.yjj.mp.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Api(tags = "用户管理接口")
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {
    @Autowired
    private MyUserService myUserService;

    //新增用户
    @PostMapping
    @ApiOperation("新增用户接口")
    public void saveUser(@RequestBody UserFormDTO userFormDTO){
        User user = new User();
        BeanUtil.copyProperties(userFormDTO,user);
        myUserService.save(user);
    }

    //删除用户
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户接口")
    public void deleteUserById(@PathVariable("id") Long id){
        myUserService.removeById(id);
    }

    //查询用户
    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户接口")
    public UserVO queryUserById(@PathVariable("id") Long id){
        User user = myUserService.getById(id);
        return BeanUtil.copyProperties(user,UserVO.class);

    }

    //批量查询用户
    @GetMapping
    @ApiOperation("根据id批量查询用户接口")
    public List<UserVO> queryUserByIds(@RequestParam ("ids") List<Long> ids){
        List<User> users = myUserService.listByIds(ids);
        return BeanUtil.copyToList(users,UserVO.class);

    }

    @PutMapping("/{id}/deduction/{money}")
    @ApiOperation("扣除用户余额接口")
    public void decuctBalance(@PathVariable("id") Long id,@PathVariable("money") Integer money){
        myUserService.deductBalance(id,money);
    }
}

service接口层:

package com.yjj.mp.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.yjj.mp.domain.po.User;

public interface MyUserService extends IService<User> {
    void deductBalance(Long id, Integer money);
}

service层:

package com.yjj.mp.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjj.mp.domain.po.User;
import com.yjj.mp.mapper.UserMapper;
import com.yjj.mp.service.MyUserService;
import org.springframework.stereotype.Service;

@Service
public class MyServiceImpl extends ServiceImpl<UserMapper, User> implements MyUserService {

    @Override
    public void deductBalance(Long id, Integer money) {
        //查询用户
        User user = getById(id);
        //校验用户状态
        if (user==null||user.getStatus()==2){
        throw   new RuntimeException("用户状态异常!");
        }
        //校验余额是否充足
        if (user.getBalance()<money){
            throw   new RuntimeException("用户余额不足!");
        }
        //扣减余额
        baseMapper.deductBalance(id,money);
    }
}

 mapper层:

package com.yjj.mp.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.yjj.mp.domain.po.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;


public interface UserMapper extends BaseMapper<User> {


   

    @Update("update user set balance=balance-#{money} where id=#{id}")
    void deductBalance(@Param("id") Long id,@Param("money") Integer money);
}

 IService的Lambda查询

实现一个根据复杂条件查询用户的接口,查询条件如下:name:用户名关键字,可以为空、status:用户状态,可以为空、minBalance:最小余额,可以为空、maxBalance:最大余额,可以为空 

controller层

 @GetMapping("/list")
    @ApiOperation("根据复杂条件查询用户接口")
    public List<UserVO> queryUsers(UserQuery query){
        List<User> users = myUserService.queryUsers(query.getName(),query.getStatus(),query.getMinBalance(),query.getMaxBalance());
        return BeanUtil.copyToList(users,UserVO.class);

    }

 service层

@Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        List<User> list = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .gt(minBalance != null, User::getBalance, minBalance)
                .lt(maxBalance != null, User::getBalance, maxBalance)
                .list();
        return list;
    }

IService的Lambda更新

改造根据id修改用户余额的接口,要求如下

  • 完成对用户状态校验
  • 完成对用户余额校验
  • 如果扣减后余额为0,则将用户status修改为冻结状态(2)

批处理方案

普通for循环逐条插入速度极差,不推荐

MyBatis-plus的批量新增,基于预编译的批处理,性能不错

配置jdbc参数,开rewriteBatchedStatements,性能最好 

 

代码生成器


这一期就到这里啦

努力遇见更好的自己!!!

  • 39
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力敲代码的小火龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值