MyBatis Plus 结合 SpringBoot 实现CRUD和批量更新

本文介绍如何使用MyBatisPlus简化MyBatis的开发流程,包括搭建环境、基本CRUD操作及批量更新,通过实例展示其强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道MyBatis是将sql语句与代码分离,存放于xml配置文件中,拼接复杂SQL语句时,拼写比较复杂,没有代码灵活。MyBatis Plus 作为mybatis的增强库,增强了mybatis的功能,让mybatis更好用,今后不需要再写SQL语句了。

一:搭建:

接下来我和大家说一下如何搭建和使用:

pom.xm

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

application.yml

#mybatis plus
mybatis-plus:
  #指明mapper.xml扫描位置(classpath* 代表编译后类文件根目录)
  mapper-locations: classpath:/mapper/*.xml
  #指明实体扫描(多个package用逗号或者分号分隔)
  typeAliasesPackage: com.fms.entity;
  global-config:
    #主键类型 0:数据库ID自增, 1:用户输入ID,2:全局唯一ID (数字类型唯一ID), 3:全局唯一ID UUID
    id-type: 0
    #字段策略(拼接sql时用于判断属性值是否拼接) 0:忽略判断,1:非NULL判断,2:非空判断
    field-strategy: 2
    #驼峰下划线转换含查询column及返回column(column下划线命名create_time,返回java实体是驼峰命名createTime,开启后自动转换否则保留原样)
    db-column-underline: true
    #是否动态刷新mapper
    refresh-mapper: false

实体类:xxx 

Mapper:XxxMapper 

mapper:XxxMapper.xml

都是和以前一样的需要,但是有两点不同:

1.启动类上需要 mybatis的包扫描路径或者@Mapper

@SpringBootApplication
@MapperScan("com.xxx.mapper.*")
public class XxxApplication {

   public static void main(String[] args) {
      SpringApplication.run(XxxApplication.class, args);
   }

}

2.继承 BaseMapper (这里的Xxx都是同一个哦)

public interface XxxMapper extends BaseMapper<Xxx> {
}

如果这个时候启动说注入有问题,试着加上@Repository

@Repository
public interface XxxMapper extends BaseMapper<Xxx> { }

二:CRDU:

启动好了以后我们就开始简单的CRUD操作:

1. select * from user where name = "aaa"  and password = "000000" and is_deleted = 0

QueryWrapper<User> queryWrapper = new QueryWrapper();
queryWrapper.lambda().eq(User::getName, requestVo.getUserName())
        .eq(User::getPassword, Tools.encryptPassword(requestVo.getPassword()))
        .eq(User::getIsDeleted,Consts.constant.ZERO);
Useruser= userMapper.selectOne(queryWrapper);

2. update user set last_login_time = "1564733558"  , login_count="10" where id = "28b296f0-fc26-454c-8c8e-68e11963d210"

user.setLastLoginTime(Integer.parseInt(Tools.timeToStamp(new Date())));
user.setLoginCount(user.getLoginCount() + Consts.constant.ONE);
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("id", user.getId());
return userMapper.update(user, updateWrapper);

以上两个例子让大家感觉一下MyBatis Plus 是怎么使用的,具体的方法大家官网上看看使用哪个方法,https://mp.baomidou.com/guide/crud-interface.html#listbyids

 

三:批量更新

我这里说批量更新是因为,在上面的更新方法大家可能觉得是对某一条做的操作但是实际上是会对满足where的条件满足的都进行更新操作,所以这里不分批量还是单一一条数据的更新!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值