欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > Mybatis-Plus的使用

Mybatis-Plus的使用

2025/4/19 11:40:33 来源:https://blog.csdn.net/2301_80079026/article/details/147287432  浏览:    关键词:Mybatis-Plus的使用

Mybatis-Plus是基于MyBatis开发的增强工具,所有Mybatis具有的功能,Mybatis-Plus全部都具有,并且帮助我们完成了基础的增删改查功能。

官⽹地址: MyBatis-Plus 🚀 为简化开发而生

1.准备工作

根据spring-boot的版本引入依赖

例如spring-boot3:

		<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId><version>3.5.5</version></dependency>

并且也需要引入mysql驱动:

		<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency>

配置数据库,以application.yml为例:

spring:datasource:url: jdbc:mysql://127.0.0.1:3307/mybatis_test2?characterEncoding=utf8&useSSL=falseusername: rootpassword: '123456'driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:configuration: # 配置打印 MyBatis⽇志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

mapper数据库层需要继承BaseMapper类,并且传入操作的表对应的实体类

@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {}

mybatis就会根据编码规范对我们的实体类的属性进行表的映射

2.简单测试CRUD介绍

    @Testvoid insert() {//插入数据UserInfo userInfo=new UserInfo();userInfo.setAge(12);userInfo.setPassword("wh");userInfo.setUsername("wang");userInfoMapper.insert(userInfo);}@Testvoid select() {//根据id或者id集合进行查询UserInfo userInfo=userInfoMapper.selectById(5);System.out.println(userInfo);List<UserInfo> list=userInfoMapper.selectBatchIds(List.of(5,6,7));list.stream().forEach(System.out::println);}@Testvoid update() {//根据id进行更新UserInfo userInfo=new UserInfo();userInfo.setId(5);userInfo.setUsername("zhangsan");System.out.println(userInfoMapper.updateById(userInfo));}@Testvoid delete() {//根据id进行删除System.out.println(userInfoMapper.deleteById(6));}

3.注解介绍

@TableName(识别实体类对应的表)

@TableField(表明属性对应字段名)

@TableId(指定对应的主键)

@Data
@TableName("user_info")//指定表名
public class UserInfo {//设置主键为自增类型的,这样才能按照自增设置主键的值@TableId(type = IdType.AUTO)private Integer id;private String username;private String password;private Integer age;private Integer gender;private String phone;@TableField("delete_flag")//指定字段名private Integer deleteFlag;private Date createTime;private Date updateTime;
}

4.条件构造器

MyBatis-Plus 提供了⼀套强⼤的条件构造器(Wrapper), ⽤于构建复杂的数据库查询条件. Wrapper 类
允许开发者以链式调⽤的⽅式构造查询条件, ⽆需编写繁琐的 SQL 语句, 从⽽提⾼开发效率并减少 SQL 注⼊的⻛险.
AbstractWrapper:这是⼀个抽象基类, 提供了所有 Wrapper 类共有的⽅法和属性. 详细参考官⽹
介绍: 条件构造器
QueryWrapper:⽤于构造查询条件, 在AbstractWrapper的基础上拓展了⼀个select⽅法, 允许指
定查询字段.
UpdateWrapper: ⽤于构造更新条件, 可以在更新数据时指定条件.
LambdaQueryWrapper:基于 Lambda 表达式的查询条件构造器, 它通过 Lambda 表达式来引⽤
实体类的属性,从⽽避免了硬编码字段名.
LambdaUpdateWrapper: 基于 Lambda 表达式的更新条件构造器, 它允许你使⽤ Lambda 表达
式来指定更新字段和条件,同样避免了硬编码字段名的问题.
lt : "less than" 的缩写,表⽰⼩于.
le : "less than or equal to"的缩写, 表⽰⼩于等于
ge : "greater than or equal to" 的缩写, 表⽰⼤于等于.
gt : "greater than" 的缩写, 表⽰⼤于.
eq : "equals" 的缩写, 表⽰等于.
ne : "not equals" 的缩写, 表⽰不等于

QueryWrapper

SELECT id,username,password,age FROM user_info WHERE age = 18 AND username 
"%min%"
@Testvoid queryWapper() {QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();queryWrapper.eq("age",18).like("username","min").select("id","username","password");List<UserInfo> list=userInfoMapper.selectList(queryWrapper);list.stream().forEach(System.out::println);}

UPDATE user_info SET delete_flag=? WHERE age < 20
 @Testvoid queryWapper2() {QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();queryWrapper.lt("age",20);UserInfo userInfo=new UserInfo();userInfo.setDeleteFlag(0);userInfoMapper.update(userInfo,queryWrapper);}

QueryWapper可以用来拼接where部分的SQL语句,但Wrapper的基础上添加了select的功能

UpdateWapper

UPDATE user_info SET delete_flag=0, age=5 WHERE id IN (5,7);
    @Testvoid updateWapper() {UpdateWrapper<UserInfo> updateWrapper=new UpdateWrapper<UserInfo>().set("delete_flag",0).set("age",5).in("id",List.of(5,7));userInfoMapper.update(updateWrapper);

直接设置SQL语句

UPDATE user_info SET age = age+10 WHERE id IN (1,2,3)
@Testvoid updateWapper2() {UpdateWrapper<UserInfo> updateWrapper=new UpdateWrapper<UserInfo>().setSql("age=age+10").in("id",List.of(1,2,3));userInfoMapper.update(updateWrapper);}

LambdaQueryWrapper和LambdaUpdateWrapper

MyBatis-Plus 给我们提供了⼀种基于Lambda表达式的条件构造器, 它通过 Lambda 表达式来引⽤实体 类的属性,从⽽避免了硬编码字段名, 也提⾼了代码的可读性和可维护性。

LambdaQueryWrapper

@Testvoid queryWapper3() {LambdaQueryWrapper<UserInfo> lambdaQueryWrapper=new LambdaQueryWrapper<UserInfo>().select(UserInfo::getId,UserInfo::getUsername,UserInfo::getPassword).lt(UserInfo::getAge,20);List<UserInfo> list = userInfoMapper.selectList(lambdaQueryWrapper);list.stream().forEach(System.out::println);}

LambdaUpdateWrapper

Testvoid updateWapper() {UpdateWrapper<UserInfo> updateWrapper=new UpdateWrapper<UserInfo>().set("delete_flag",0).set("age",5).in("id",List.of(5,7));userInfoMapper.update(updateWrapper);}

5.自定义SQL

在实际的开发中, MyBatis-Plus提供的操作不能满⾜我们的实际需求, MyBatis-Plus 也提供了⾃定义
SQL的功能, 我们可以利⽤Wrapper构造查询条件, 再结合Mapper编写SQL,mybatis-plus的版本不得低于3.0.7。也可以全部自己写,注解和XML的形式都和mybatis一摸一样
使用Wrapper和自定义SQL结合版:

使用注解的方式:

参数Wrapper必须命名为ew,用Param注解,直接写ew或者使用常量类Constants.WAPPER

SQL用${ew.customSqlSegment}的方式传入参数

@Select("select * from user_info ${ew.customSqlSegment}")List<UserInfo> selectList(@Param(Constants.WRAPPER) Wrapper wrapper);//常量Constants.WRAPPER就是ew
LambdaUpdateWrapper<UserInfo> wrapper=new LambdaUpdateWrapper<UserInfo>().eq(UserInfo::getAge,10);userInfoMapper.selectList(wrapper);

使用XML的形式:

配置mapper路径:

mybatis-plus:mapper-locations: "classpath*:/mapper/**.xml" # Mapper.xml

定义方法:

List<UserInfo> selectList2(@Param(Constants.WRAPPER) Wrapper wrapper);

编写XML

<select id="selectList2" resultType="com.bit.mybatisplus.model.UserInfo">select * from user_info ${ew.customSqlSegment}</select>

测试

@Testvoid selectList() {LambdaQueryWrapper<UserInfo> wrapper=new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getAge,10);//userInfoMapper.selectList(wrapper);//userInfoMapper.selectList2((Wrapper) wrapper);userInfoMapper.selectList2( wrapper);}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词