威海市网站建设_网站建设公司_测试上线_seo优化
2026/1/16 16:44:30 网站建设 项目流程

文章目录

  • 快速上手
    • 一、引入依赖 && 配置
    • 二、编码
  • 复杂操作
    • 一、常见注解
      • 1. `@TableName`
      • 2. `@TableField`
      • 3. `@TableId`
    • 二、打印日志
    • 三、条件构造器
      • 1. `QueryWrapper`
        • **查询**
        • **更新**
        • **删除**
      • 2. UpdateWrapper
      • 3. LambdaQueryWrapper
      • 4. LambdaUpdateWrapper
    • 四、自定义SQL
      • **代码示例1**
      • **代码示例2**
      • **代码示例3**


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

快速上手

一、引入依赖 && 配置

SpringBoot2

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

SpringBoot3

<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:3306/mybatis_test?characterEncoding=utf8&useSSL=falseusername:rootpassword:rootdriver-class-name:com.mysql.cj.jdbc.Driver

二、编码

创建实体类 UserInfo:

实体类的属性名与表中的字段名一一对应

importlombok.Data;importjava.util.Date;@DatapublicclassUserInfo{privateIntegerid;privateStringusername;privateStringpassword;privateIntegerage;privateIntegergender;privateStringphone;privateIntegerdeleteFlag;privateDatecreateTime;privateDateupdateTime;}

编写 Mapper 接口类:

MybatisPlus提供了一个基础的BaseMapper接口,已经实现了单表的CRUD我们自定义的Mapper只需要继承这个BaseMapper,就无需自己实现单表CRUD了,如下所示:

@MapperpublicinterfaceUserInfoMapperextendsBaseMapper<UserInfo>{}

也可以在启动类上添加@MapperScan,扫描Mapper文件夹,二选一即可。

复杂操作

一、常见注解

在上面的程序中,MyBatis是如何知道,我们要操作的是哪张表,表里有哪些字段呢?

我们来看下咱们Mapper的代码:

@MapperpublicinterfaceUserInfoMapperextendsBaseMapper<UserInfo>{}

UserInfoMapper在继承BaseMapper时,指定了一个泛型,这个UserInfo就是与数据库表相对应的实体类。

MyBatis-Plus会根据这个实体类来推断表的信息。

默认情况下:

  1. 表名:实体类的驼峰表示法 -> 蛇形表示法作为表名。比如UserInfo->user_info
  2. 字段:实体类的属性名 -> 蛇形表示法作为字段名。比如deleteFlag->delete_flag
  3. 主键:默认为id

那如果实体类和数据库不是按照上述规则定义的呢?MyBatis-Plus也给我们提供了一下注解,让我们标识表的信息。

1.@TableName

通过@TableName来标识实体类对应的表:

@Data@TableName("user_info")publicclassUserinfo{privateIntegerid;privateStringusername;privateStringpassword;privateIntegerage;privateIntegergender;privateStringphone;privateIntegerdeleteFlag;privateDatecreateTime;privateDateupdateTime;}

2.@TableField

通过@TableField来标识对应的字段名:

@DatapublicclassUserinfo{privateIntegerid;privateStringusername;privateStringpassword;privateIntegerage;privateIntegergender;privateStringphone;@TableField("delete_flag")// 定义和数据库字段名相同privateIntegerdeleteflag;privateDatecreateTime;privateDateupdateTime;}

3.@TableId

通过@TableId来指定对应的主键:

@DatapublicclassUserinfo{@TableId("id",type=IdType.AUTO)privateIntegeruserId;privateStringusername;privateStringpassword;privateIntegerage;privateIntegergender;privateStringphone;privateIntegerdeleteflag;privateDatecreateTime;privateDateupdateTime;}
  1. 如果属性名和字段名一致,直接加@TableId注解就可以
  2. 如果属性名和字段名不一致,需要在@TableId指明对应的字段名

常见的IdType类型如下所示:

  1. AUTO
    1. 数据库自增 ID(通常配合MySQLAUTO_INCREMENT)。
    2. 由数据库生成,插入时不需要自己赋值。
  2. NONE(默认值)
    1. 不设置主键类型,MyBatis-Plus 不会自动处理,走数据库自身策略。
  3. INPUT
    1. 主键由你自己传入(手动 set)。
  4. ASSIGN_ID
    1. MyBatis-Plus 内置的全局唯一 ID 生成器(类似雪花算法),适合分布式系统。
    2. 插入前自动生成。
  5. ASSIGN_UUID
    1. 自动生成一个UUID字符串作为主键。

二、打印日志

在配置文件中添加如下内容:

mybatis-plus:configuration:# 配置打印 MyBatis日志log-impl:org.apache.ibatis.logging.stdout.StdOutImpl

三、条件构造器

条件构造器

MyBatis-Plus 提供了一套强大的条件构造器 Wrapper,用于构建复杂的数据库查询条件。Wrapper 类允许开发者以链式调用的方式构造查询条件,无需编写繁琐的 SQL 语句,从而提高开发效率并减少 SQL 注入的风险。

以下是主要的 Wrapper 类及其功能:

  • AbstractWrapper:这是一个抽象基类,提供了所有Wrapper类共有的方法和属性。
  • QueryWrapper:用于构造查询条件,在AbstractWrapper的基础上拓展了一个select方法,允许指定查询字段。
  • UpdateWrapper:用于构造更新条件,可以在更新数据时指定条件。
  • LambdaQueryWrapper:基于Lambda表达式的查询条件构造器,它通过Lambda表达式来引用实体类的属性,从而避免了硬编码字段名。
  • LambdaUpdateWrapper:基于Lambda表达式的更新条件构造器,它允许你使用Lambda表达式来指定更新字段和条件,同样避免了硬编码字段名的问题。

1.QueryWrapper

查询

完成下述SQL查询:

SELECTid,username,password,ageFROMuser_infoWHEREage=18ANDusernameLIKE"%min%"

测试代码:

@TestvoidtestQueryWrapper(){QueryWrapper<UserInfo>userInfoQueryWrapper=newQueryWrapper<UserInfo>().select("id","username","password","age").eq("age",18).like("username","min");List<UserInfo>userInfos=userInfoMapper.selectList(userInfoQueryWrapper);userInfos.forEach(System.out::println);}

💥注意:

默认情况下 Mybatis-Plus 会根据@TableFiled生成别名,当指定了QueryWrapperselect属性后就仅仅是属性值而没有了别名。查询出来的结果会对应不上。

更新

完成下述SQL查询:

UPDATEuser_infoSETdelete_flag=?WHEREage<20

测试代码:

@TestvoidtestUpdateByQueryWrapper(){QueryWrapper<UserInfo>userInfoQueryWrapper=newQueryWrapper<UserInfo>().lt("age",20);UserInfouserInfo=newUserInfo();userInfo.setDeleteFlag(1);userInfoMapper.update(userInfo,userInfoQueryWrapper);}
  • lt:“less than” 的缩写,表示小于
  • le:“less than or equal to” 的缩写,表示小于等于
  • ge:“greater than or equal to” 的缩写,表示大于等于
  • gt:“greater than” 的缩写,表示大于
  • eq:“equals” 的缩写,表示等于
  • ne:“not equals” 的缩写,表示不等于
删除

完成下述SQL查询:

DELETEFROMuser_infoWHEREage=18

测试代码:

@TestvoidtestDeleteByQueryWrapper(){QueryWrapper<UserInfo>userInfoQueryWrapper=newQueryWrapper<UserInfo>().eq("age",18);userInfoMapper.delete(userInfoQueryWrapper);}

2. UpdateWrapper

对于更新,可以直接使用UpdateWrapper,在不创建实体对象的情况下,直接设置更新字段和条件。

完成下述SQL查询:

UPDATEuser_infoSETdelete_flag=0,age=5WHEREidIN(1,2,3)

测试代码:

@TestvoidtestUpdateByUpdateWrapper(){UpdateWrapper<UserInfo>updateWrapper=newUpdateWrapper<UserInfo>().set("delete_flag",0).set("age",5).in("id",List.of(1,2,3));userInfoMapper.update(updateWrapper);}

完成下述SQL查询:

UPDATEuser_infoSETage=age+10WHEREidIN(1,2,3)

测试代码:

@TestvoidtestUpdateBySQLUpdateWrapper(){UpdateWrapper<UserInfo>updateWrapper=newUpdateWrapper<UserInfo>().setSql("age = age+10").in("id",List.of(1,2,3));userInfoMapper.update(updateWrapper);}

3. LambdaQueryWrapper

QueryWrapperUpdateWrapper存在一个问题,就是需要写死字段名,如果字段名发生变更,可能会因为测试不到位酿成事故。

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

接下来我们看下具体使用:

@TestvoidtestLambdaQueryWrapper(){QueryWrapper<UserInfo>queryWrapper=newQueryWrapper<UserInfo>();queryWrapper.lambda().select(UserInfo::getUsername,UserInfo::getPassword,UserInfo::getAge).eq(UserInfo::getUserId,1);userInfoMapper.selectList(queryWrapper).forEach(System.out::println);}

4. LambdaUpdateWrapper

@TestvoidtestLambdUpdateByUpdateWrapper(){UpdateWrapper<UserInfo>updateWrapper=newUpdateWrapper<UserInfo>();updateWrapper.lambda().set(UserInfo::getDeleteFlag,0).set(UserInfo::getAge,5).in(UserInfo::getUserId,List.of(1,2,3));userInfoMapper.update(updateWrapper);}

四、自定义SQL

在实际的开发中,MyBatis-Plus 提供的操作可能不能满足我们的实际需求,MyBatis-Plus 也提供了自定义 SQL 的功能,我们可以利用Wrapper构造查询条件,再结合Mapper编写SQL

📌 为了使用这一功能,mybatis-plus 版本不低于 3.0.7

代码示例1

完成下述SQL查询:

selectid,username,password,ageFROMuser_infoWHEREusername="admin"

Mapper:

@MapperpublicinterfaceUserInfoMapperextendsBaseMapper<UserInfo>{@Select("select id,username,password,age FROM user_info ${ew.customSqlSegment}")List<UserInfo>queryUserByCustom(@Param(Constants.WRAPPER)Wrapper<UserInfo>wrapper);}

测试代码:

@TestvoidtestQueryUserByCustom(){QueryWrapper<UserInfo>queryWrapper=newQueryWrapper<UserInfo>().eq("username","admin");userInfoMapper.queryUserByCustom(queryWrapper).forEach(System.out::println);}

💥注意事项:

  • 参数命名:在自定义 SQL 传递 Wrapper 对象作为参数时,参数名必须为ew,或者使用注解@Param(Constants.WRAPPER)明确指定参数为 Wrapper 对象
  • 在SQL语句中,使用${ew.customSqlSegment}来引用 Wrapper 对象生成的 SQL 片段。
  • 不支持基于 entity 的 where 语句:自定义 SQL 时,Wrapper 对象不会基于实体类自动生成 where 子句,你需要手动编写完整的 SQL 语句。

代码示例2

MyBatis-Plus 在 MyBatis 的基础上只做增强不做改变,所以也支持XML的实现方式。

上述功能也可以使用XML的方式完成:

  1. 配置mapper路径

    mybatis-plus:mapper-locations:"classpath*:/mapper/**.xml"# Mapper.xml
  2. 定义方法

    @MapperpublicinterfaceUserInfoMapperextendsBaseMapper<UserInfo>{List<UserInfo>queryUserByCustom2(@Param(Constants.WRAPPER)Wrapper<UserInfo>wrapper);}
  3. 编写XML

    <?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.bite.mybatis.plus.mapper.UserInfoMapper"><selectid="queryUserByCustom2">select id,username,password,age FROM user_info ${ew.customSqlSegment}</select></mapper>
  4. 测试

    @TestvoidtestQueryUserByCustom2(){QueryWrapper<UserInfo>queryWrapper=newQueryWrapper<UserInfo>().eq("username","admin");userInfoMapper.queryUserByCustom2(queryWrapper).forEach(System.out::println);}

代码示例3

完成下述 SQL 查询:

UPDATEuser_infoSETage=age+10WHEREidIN(1,2,3)

Mapper:

@Update("UPDATE user_info SET age = age+ #{addAge} ${ew.customSqlSegment}")voidupdateUserByCustom(@Param("addAge")intaddAge,@Param("ew")Wrapper<UserInfo>wrapper);

测试代码:

@TestvoidupdateUserByCustom(){QueryWrapper<UserInfo>queryWrapper=newQueryWrapper<UserInfo>().in("id",List.of(1,2,3));userInfoMapper.updateUserByCustom(10,queryWrapper);}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询