今日目标:
- 了解mybatisplus的特点
- 能够掌握mybatisplus快速入门
- 能够掌握mybatisplus常用注解
- 能够掌握mybatisplus常用的增删改查
- 能够掌握mybatisplus自动代码生成
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网:https://mybatis.plus/ 或 https://mp.baomidou.com/
版本
2 快速入门com.baomidou mybatis-plus 3.4.2
SpringBoot 整合 MyBatis-Plus,并实现根据Id查询功能。
1、数据库环境准备 2、创建SpringBoot工程,引入MyBatis-Plus场景依赖 3、编写DataSource相关配置 4、编写mapper 5、测试2.1 数据库环境准备
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for tb_user 没有给自增 -- ---------------------------- DROp TABLE IF EXISTS `tb_user`; CREATE TABLE `tb_user` ( `id` bigint(20) NOT NULL, `user_name` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `t_name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of tb_user -- ---------------------------- BEGIN; INSERT INTO `tb_user` VALUES (1, '赵一伤', '123456', 'zys', 19, 'zys@itcast.cn'); INSERT INTO `tb_user` VALUES (2, '钱二败', '123456', 'qes', 18, 'qes@itcast.cn'); INSERT INTO `tb_user` VALUES (3, '孙三毁', '123456', 'ssh', 20, 'ssh@itcast.cn'); INSERT INTO `tb_user` VALUES (4, '李四摧', '123456', 'lsc', 20, 'lsc@itcast.cn'); INSERT INTO `tb_user` VALUES (5, '周五输', '123456', 'zws', 20, 'zws@itcast.cn'); INSERT INTO `tb_user` VALUES (6, '吴六破', '123456', 'wlp', 21, 'wlp@itcast.cn'); INSERT INTO `tb_user` VALUES (7, '郑七灭', '123456', 'zqm', 22, 'zqm@itcast.cn'); INSERT INTO `tb_user` VALUES (8, '王八衰', '123456', 'wbs', 22, 'wbs@itcast.cn'); INSERT INTO `tb_user` VALUES (9, '张无忌', '123456', 'zwj', 25, 'zwj@itcast.cn'); INSERT INTO `tb_user` VALUES (10, '赵敏', '123456', 'zm', 26, 'zm@itcast.cn'); INSERT INTO `tb_user` VALUES (11, '赵二伤', '123456', 'zes', 25, 'zes@itcast.cn'); INSERT INTO `tb_user` VALUES (12, '赵三伤', '123456', 'zss1', 28, 'zss1@itcast.cn'); INSERT INTO `tb_user` VALUES (13, '赵四伤', '123456', 'zss2', 29, 'zss2@itcast.cn'); INSERT INTO `tb_user` VALUES (14, '赵五伤', '123456', 'zws', 39, 'zws@itcast.cn'); INSERT INTO `tb_user` VALUES (15, '赵六伤', '123456', 'zls', 29, 'zls@itcast.cn'); INSERT INTO `tb_user` VALUES (16, '赵七伤', '123456', 'zqs', 39, 'zqs@itcast.cn'); COMMIT; SET FOREIGN_KEY_CHECKS = 1;2.2 创建工程,引入场景依赖
2.3 编写DataSource相关配置org.springframework.boot spring-boot-starter-parent 2.3.10.RELEASE 1.8 mysql mysql-connector-java 5.1.26 org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.baomidou mybatis-plus-boot-starter 3.4.2
# datasource
spring:
datasource:
url: jdbc:mysql://192.168.200.150:3306/mp?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
2.4 编码
实体类:
package com.itheima.sh.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("tb_user") // 指定表名
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
@TableName("tb_user”) : 如果数据库的表名和实体类一致时可以省略
编写mapper:
package com.itheima.sh.mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.itheima.sh.pojo.User; public interface UserMapper extends baseMapper{ //crud insert delete update select }
启动类增加 @MapperScan 注解
package com.itheima.sh;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.itheima.sh.mapper")
public class MpApplication {
public static void main(String[] args) {
SpringApplication.run(MpApplication.class, args);
}
}
2.5 测试
package com.itheima.sh;
import com.itheima.sh.mapper.UserMapper;
import com.itheima.sh.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectById() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
}
3 CRUD
入门程序中 Mapper 继承 baseMapper:
3.1 新增 3.1.1 方法解析 3.1.2 测试@Test
public void testInsert() {
User user =
User.builder()
.userName("itheima")
.name("itcast")
.age(15)
.email("itcast@itcast.cn")
.password("111111")
.build();
int insert = userMapper.insert(user);
System.out.println(insert);
}
3.1.3 主键生成策略-@TableId
作用:标识数据库的主键列以及主键生成的策略
使用:添加在实体类的主键对应的成员属性
主键生成策略探究:
@documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface TableId {
String value() default "";
IdType type() default IdType.NONE; // 默认是 NONE
}
// IdType
@Getter
public enum IdType {
AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
// 省略部分代码.....
}
3.1.4 普通列注解- @TableField
作用:
1)@TableField(“user_name”) 指定映射关系
以下情况可以省略:
- 名称一样
- 数据库字段使用_分割,实体类属性名使用驼峰名称
2)忽略某个字段的查询和插入 @TableField(exist = false)
3.1.5 具体使用
@TableName("tb_user")
@Data
public class User {
//设置id生成策略:AUTO 数据库自增
@TableId(type = IdType.AUTO)
private Long id;
//@TableField("user_name")
private String userName;
private String password;
@TableField("t_name")
private String name;
private Integer age;
private String email;
//不希望该值存入数据库
// @TableField(exist = false)
// private String address;
}
3.2 删除
3.2.1 根据id删除
int count = userMapper.deleteById(8L);3.2.2 根据id集合批量删除
List ids = new ArrayList();
ids.add(6);
ids.add(7);
userMapper.deleteBatchIds(ids);
3.2.3 根据map构造条件,删除
Map3.2.4 根据wrapper构造条件,删除map = new HashMap<>(); //delete from tb_user where user_name = ? and age = ? map.put("user_name","itcast"); map.put("age","18"); userMapper.deleteByMap(map);
//1.创建查询条件构建器 QueryWrapper3.3 更新wrapper = new QueryWrapper<>(); //2.设置条件 //delete from tb_user where user_name = ? and age = ? wrpper.eq("userName","lisi") .gt("age","11"); userMapper.delete(wrapper);
@Test
public void testUpdateById() {
User user = new User();
user.setId(2L);
user.setPassword("1111111");
int count = userMapper.updateById(user);
}
4 查询
4.1 分页查询
配置 拦截器
package com.itheima.sh.config;
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 {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setMaxLimit(-1L);
// 开启 count 的 join 优化,只针对部分 left join
interceptor.addInnerInterceptor(paginationInterceptor);
return interceptor;
}
}
查询
@Test
public void testSelectPage() {
int current = 1;//当前页码
int size = 2;//每页显示条数
IPage page = new Page(current,size);
userMapper.selectPage(page,null);
List records = page.getRecords();//当前页的数据
long pages = page.getPages();//总页数 2
long total = page.getTotal();//总记录数 4
System.out.println(records);
System.out.println(pages);
System.out.println(total);
}
4.2 条件构造器查询
4.2.1 基础查询
通过 QueryWrapper 指定查询条件
eq( ) : 等于 = ne( ) : 不等于 <> gt( ) : 大于 > ge( ) : 大于等于 >= lt( ) : 小于 < le( ) : 小于等于 <= between ( ) : BETWEEN 值1 AND 值2 notBetween ( ) : NOT BETWEEN 值1 AND 值2 in( ) : in notIn( ) :not in
@Test
public void testWrapper1() throws Exception{
QueryWrapper wrapper = new QueryWrapper<>();
// 封装查询条件
wrapper.like("user_name", "%伤%")
.eq("password","123456")
.in("age",19,25,29)
.orderByDesc("age","id"); // 降序 升序:asc
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.2 逻辑查询 or
or( ) :让紧接着下一个方法用or连接
@Test
public void testWrapper2(){
//1.创建查询条件构建器
QueryWrapper wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五");
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.3 模糊查询 like
like notLike likeLeft likeRight
@Test
public void testWrapper3(){
//1.创建查询条件构建器
QueryWrapper wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.likeLeft("user_name","zhang");
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.4 排序查询
orderBy orderByAsc orderByDesc
@Test
public void testWrapper4(){
//1.创建查询条件构建器
QueryWrapper wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五")
//.orderBy(true,true,"age")
.orderByDesc("age");
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.5 select:指定需要查询的字段
@Test
public void testWrapper5(){
//1.创建查询条件构建器
QueryWrapper wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五")
//.orderBy(true,true,"age")
.orderByDesc("age")
.select("id","user_name");
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.6 分页条件查询
@Test
public void testWrapper6(){
int current = 1;//当前页码
int size = 2;//每页显示条数
//1. 构建分页对象
Page page = new Page<>(current,size);
//2. 构建条件对象
QueryWrapper wrapper = new QueryWrapper();
wrapper.lt("age",23);
userMapper.selectPage(page,wrapper);
List records = page.getRecords();
long total = page.getTotal();
long pages = page.getPages();
System.out.println(records);
System.out.println(total);//2
System.out.println(pages);//1
}
4.2.7 LambdaQueryWrapper
目的:消除代码中的硬编码
@Test
public void testWrapper4() throws Exception{
// LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery();
// wrapper.like("user_name", "%伤%")
// .eq("password","123456")
// .ge("age", 28)
// .between("age",29 , 39); // 包含边界值
wrapper.like(User::getUserName, "%伤%")
.eq(User::getPassword, "123456")
.ge(User::getAge, 28)
.between(User::getAge, 29, 39)
.orderByDesc(User::getAge)
.select(User::getId, User::getUserName);
List users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.2.8 条件删除
@Test
public void testWrapper5() throws Exception{
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery().eq(User::getUserName, "武大郎");
int i = userMapper.delete(wrapper);
System.out.println(i);
}
4.2.9 条件 update
@Test
public void testWrapper6() throws Exception{
// 参数1: 最新的值
User user = new User();
user.setUserName("张三丰");
// 参数2:更新时条件
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery();
wrapper.eq(User::getId, 15);
int update = userMapper.update(user, wrapper);
System.out.println(update);
}
@Test
public void testWrapper7() throws Exception{
// 参数1: 最新的值
// 参数2:更新时条件
LambdaUpdateWrapper wrapper = Wrappers.lambdaUpdate();
wrapper.eq(User::getId, 15)
.set(User::getUserName, "张三丰666")
.set(User::getName,"zsf666");
int update = userMapper.update(null, wrapper);
System.out.println(update);
}
5 service 封装
Mybatis-Plus 为了开发更加快捷,对业务层也进行了封装,直接提供了相关的接口和实现类。我们在进行业务层开发时,可以继承它提供的接口和实现类,使得编码更加高效
- 1. 定义接口继承IService - 2. 定义实现类继承ServiceImpl实现定义的接口
接口
public interface UserService extends IService{ }
实现类封装
@Service public class UserServiceImpl extends ServiceImplimplements UserService {}
crud save remove update (list get query 没有select)
编写Controller,使用PostMan测试
package com.itheima.sh.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
UserService userService;
@PostMapping
public User add( @RequestBody User user) {
userService.save(user); // 保存成功, 主键会自动封装到 User的主键属性上
return user;
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable("id") Long id) {
return userService.removeById(id);
}
@PutMapping("/{id}")
public boolean update(@PathVariable("id") Long id,@RequestBody User user) {
return userService.update(user, Wrappers.lambdaQuery().eq(User::getId, id));
}
@GetMapping("/{id}")
public User findOne(@PathVariable("id") Long id) {
return userService.getById(id);
}
@PostMapping("findList")
public List findList(@RequestBody User user) {
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery();
if (user.getUserName()!=null && user.getUserName().length() > 0) {
wrapper.like(User::getUserName, user.getUserName());
}
if (user.getAge() != null) {
wrapper.eq(User::getAge, user.getAge());
}
List list = userService.list(wrapper);
return list;
}
@PostMapping("findPage/{page}/{size}")
public Page findPage(@PathVariable("page") Long current, @PathVariable("size") Long size,
@RequestBody User user) {
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery();
if (user.getUserName()!=null && user.getUserName().length() > 0) {
wrapper.like(User::getUserName, user.getUserName());
}
if (user.getAge() != null) {
wrapper.eq(User::getAge, user.getAge());
}
Page page = new Page<>(current,size);
return userService.page(page,wrapper);
}
}
6 逆向工程-代码生成器
6.1 代码生成说明
当有一个新的业务实现时,对接口的功能实现上,我们通常来说需要构建下面的信息:
-
PO类
数据库表和实体类的映射 Java Bean。
-
DAO层
需要编写接口 Mapper ,接口 Mapper 需要去继承 MP 中的 baseMapper 接口。
-
Service层
编写 Service 层接口和实现类。业务接口需要去继承 MP 中的 IService,业务实现类需要继承 MP 中的 ServiceImpl 和 实现业务接口。
-
Controller层
编写 Controller 并标注 Spring MVC 中的相关注解。
从上面的各类代码中可以放下,代码都是模板性的,如果用手工copy、修改的方式来实现,太烦人也没效率,而这时就是代码生成器小展身手的时候,使用代码生成器生成模板性的代码,减少手工操作的繁琐,集中精力在业务开发上,提升开发效率。
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Mapper接口、Entity实体类、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
6.2 代码生成导入资料中已提供完整的代码
或者是gitee开源链接:https://gitee.com/jitheima/mp_generator.git
完整代码:
以后在项目中使用,在这里生成后,可以把代码拷贝到对应的目录里使用,在整个黑马头条项目开发阶段,使用了当前生成的mapper和实体类。
7 MybatisX插件MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装。
功能:
- Java 与 XML 调回跳转
- Mapper 方法自动生成 XML



