1. 首先引入maven依赖
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.28</version><scope>provided</scope>
</dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.2</version>
</dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version>
</dependency>
2. 添加数据库配置信息 application.properties
MyBatisPlus支持如下数据库:
mysql 、mariadb 、oracle 、db2、 h2、 hsql 、sqlite 、postgresql 、sqlserver
达梦数据库 虚谷数据库 人大金仓数据库
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus-demo
spring.datasource.username = root
spring.datasource.password = root# 打印执行sql
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3. 启动类添加扫描Mapper文件的注解
@MapperScan("com.demo.*.mapper")
4. 接口需要继承 BaseMapper 泛型传入实体类
public interface DemoMapper extends BaseMapper<Demo> {}
5. 测试查询 xml都不用写
@SpringBootTest
class MybatisPlusDemoTests {@Autowiredprivate DemoMapper demoMapper;@Testpublic void testSelect() {// wrapper.like("name",666);// 大于等于ge("name",100)// 自定义 apply("name like {0} and age>={1}","%张%",18);// 只返回id和name两个字段wrapper.select("id","name");// 查询所有数据List<User> list = demoMapper.selectList(null);list.forEach(System.out::println);}@Testpublic void testInsert() {User= new User(null,2,3)int rs = demoMapper.insert(demo);System.out.println("成功插入条数:"+rs+"插入的主键id:"+demo.getId());}@Testpublic void testUpdateById() {// 只修改不为空的字段int rs = demoMapper.updateById(new User(1,7,8));System.out.println("修改成功的条数:"+ rs);}@Testpublic void testUpdateQueryCondition() {UpdateWrapper<User> wrapper = new UpdateWrapper<>();// 根据条件更新wrapper.eq("name",7);int rs = demoMapper.update(new User(null,7,8),wrapper);System.out.println("修改成功的条数:"+ rs);}@Testpublic void testDeleteById() {// 根据id删除int rs = demoMapper.deleteById(1);System.out.println("删除成功的条数:"+ rs);}@Testpublic void testDeleteQueryCondition() {// 根据name删除 还可以批量删除 deleteBatchIds(Collection<?> idList);UpdateWrapper<User> wrapper = new UpdateWrapper<>();wrapper.eq("name",1);int rs = userMapper.delete(wrapper);System.out.println("删除成功的条数:"+ rs);}@Testpublic void testQueryWrapper1() {// 使用LambdaQueryWrapper实现类可以使用lambda表达式// LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();//LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();LambdaQueryWrapper<User> wrapper = new QueryWrapper().lambda();wrapper.like(User::getName,1);List<User> demoList = demoMapper.selectList(wrapper);demoList.forEach(System.out::println);}@Testpublic void testQueryWrapper6() {// 指定要查询的字段LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();wrapper.select(User::getId,User::getName);wrapper.like(User::getName,"张");List<User> userList = userMapper.selectList(wrapper);userList.forEach(System.out::println);}@Testpublic void testQueryWrapper7() {// condition动态条件拼接LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();String name = "张";wrapper.like(name != null,User::getName,"张");List<User> userList = userMapper.selectList(wrapper);userList.forEach(System.out::println);}@Testpublic void testQueryWrapper8() {// 链式拼接条件LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();wrapper.select(User::getId,User::getName);wrapper.like(User::getName,"张").eq(User::getEmail,"aa@qq.com");List<User> userList = userMapper.selectList(wrapper);userList.forEach(System.out::println);}}
6. 分页查询
先增加配置类
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig {// 最新版@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}// 旧版
// @Bean
// public PaginationInterceptor paginationInterceptor() {
// PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// // paginationInterceptor.setOverflow(false);
// // 设置最大单页限制数量,默认 500 条,-1 不受限制
// // paginationInterceptor.setLimit(500);
// // 开启 count 的 join 优化,只针对部分 left join
// paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
// return paginationInterceptor;
// }}
@Test
public void testSelectPage() {// 这里会执行两次的SQL,先查询符合条件的总记录数,再通过limit查询出分页数据。QueryWrapper<User> wrapper = new QueryWrapper();IPage<User> page = new Page<>(2,3);page = userMapper.selectPage(page,wrapper);long total = page.getTotal();//总条数long pageNum = page.getCurrent();//当前页码long pageSize = page.getSize();//每页显示条数List<User> records = page.getRecords();//记录数据System.out.println("total:"+total+",pageNum:"+pageNum+",pageSize:"+pageSize);
}
7.Service接口继承IService
定义一个接口如UserService,继承接口IService<T>
import com.baomidou.mybatisplus.extension.service.IService;
import com.kfit.user.model.User;public interface UserService extends IService<User> {}
8.Service实现类继承ServiceImpl
定义服务接口UserService的实现类UserServiceImpl,并且继承实现类ServiceImpl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kfit.user.mapper.UserMapper;
import com.kfit.user.model.User;
import com.kfit.user.service.UserService;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}
9. 注解
@TableName("sys_user") //表名注解,标识实体类对应的表
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 表名 |
schema | String | 否 | "" | schema |
keepGlobalPrefix | boolean | 否 | false | 是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时) |
resultMap | String | 否 | "" | xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定) |
autoResultMap | boolean | 否 | false | 是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入) |
excludeProperty | String[] | 否 | {} | 需要排除的属性名 @since 3.3.1 |
关于 autoResultMap 的说明:
MP 会自动构建一个 resultMap 并注入到 MyBatis 里(一般用不上),请注意以下内容:
因为 MP 底层是 MyBatis,所以 MP 只是帮您注入了常用 CRUD 到 MyBatis 里,注入之前是动态的(根据您的 Entity 字段以及注解变化而变化),但是注入之后是静态的(等于 XML 配置中的内容)。
而对于 typeHandler 属性,MyBatis 只支持写在 2 个地方:
(1)定义在 resultMap 里,作用于查询结果的封装
(2)定义在 insert 和 update 语句的 #{property} 中的 property 后面(例:#{property,typehandler=xxx.xxx.xxx}),并且只作用于当前 设置值
除了以上两种直接指定 typeHandler 的形式,MyBatis 有一个全局扫描自定义 typeHandler 包的配置,原理是根据您的 property 类型去找其对应的 typeHandler 并使用。
@TableId(type = IdType.AUTO) // 字段主键注解
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 主键字段名 |
type | Enum | 否 | IdType.NONE | 指定主键类型 |
IdType枚举值:
值 | 描述 |
AUTO | 数据库 ID 自增 |
NONE | 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) |
INPUT | insert 前自行 set 主键值 |
ASSIGN_ID | 分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口 |
ASSIGN_UUID | 分配 UUID,主键类型为 String(since 3.3.0),使用接口 |
ID_WORKER | 分布式全局唯一 ID 长整型类型(please use |
UUID | 32 位 UUID 字符串(please use |
ID_WORKER_STR | 分布式全局唯一 ID 字符串类型(please use |
@TableField // 字段注解(非主键)
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 数据库字段名 |
exist | boolean | 否 | true | 是否为数据库表字段 |
condition | String | 否 | "" | 字段 |
update | String | 否 | "" | 字段 |
insertStrategy | Enum | 否 | FieldStrategy.DEFAULT | 举例:NOT_NULL |
updateStrategy | Enum | 否 | FieldStrategy.DEFAULT | 举例:IGNORED |
whereStrategy | Enum | 否 | FieldStrategy.DEFAULT | 举例:NOT_EMPTY |
fill | Enum | 否 | FieldFill.DEFAULT | 字段自动填充策略 |
select | boolean | 否 | true | 是否进行 select 查询 |
keepGlobalFormat | boolean | 否 | false | 是否保持使用全局的 format 进行处理 |
jdbcType | JdbcType | 否 | JdbcType.UNDEFINED | JDBC 类型 (该默认值不代表会按照该值生效) |
typeHandler | Class<? extends TypeHandler> | 否 | UnknownTypeHandler.class | 类型处理器 (该默认值不代表会按照该值生效) |
numericScale | String | 否 | "" | 指定小数点后保留的位数 |
关于`jdbcType`和`typeHandler`以及`numericScale`的说明:
numericScale只生效于 update 的 sql. jdbcType和typeHandler如果不配合@TableName#autoResultMap = true一起使用,也只生效于 update 的 sql. 对于typeHandler如果你的字段类型和 set 进去的类型为equals关系,则只需要让你的typeHandler让 Mybatis 加载到即可,不需要使用注解
FieldStrategy
值 | 描述 |
IGNORED | 忽略判断 |
NOT_NULL | 非 NULL 判断 |
NOT_EMPTY | 非空判断(只对字符串类型字段,其他类型字段依然为非 NULL 判断) |
DEFAULT | 追随全局配置 |
NEVER | 不加入SQL |
FieldFill
值 | 描述 |
DEFAULT | 默认不处理 |
INSERT | 插入时填充字段 |
UPDATE | 更新时填充字段 |
INSERT_UPDATE | 插入和更新时填充字段 |
@Version // 乐观锁注解
@TableLogic // 表字段逻辑处理注解(逻辑删除)
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 逻辑未删除值 |
delval | String | 否 | "" | 逻辑删除值 |
@OrderBy // 内置 SQL 默认指定排序,优先级低于 wrapper 条件查询
属性 | 类型 | 必须指定 | 默认值 | 描述 |
isDesc | boolean | 否 | true | 是否倒序查询 |
sort | short | 否 | Short.MAX_VALUE | 数字越小越靠前 |