MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生
开发环境
IDE:idea 2019.2
JDK:JDK8
构建工具:maven 3.x
MySQL版本:MySQL 8.0.27
Spring Boot:2.5.8
MyBatis-Plus:3.5.1
创建表
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER
SET utf8mb4 */;
USE `mybatis_plus`;
CREATE TABLE `user` (
`id` BIGINT ( 20 ) NOT NULL COMMENT '主键ID',
`name` VARCHAR ( 30 ) DEFAULT NULL COMMENT '姓名',
`age` INT ( 11 ) DEFAULT NULL COMMENT '年龄',
`email` VARCHAR ( 50 ) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8;
添加数据
INSERT INTO USER ( id, NAME, age, email )
VALUES
( 1, 'Jone', 18, '[email protected]' ),
( 2, 'Jack', 20, '[email protected]' ),
( 3, 'Tom', 28, '[email protected]' ),
( 4, 'Sandy', 21, '[email protected]' ),
( 5, 'Billie', 24, '[email protected]' );
引入依赖
新建spring boot项目并引入依赖
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.10version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
yml文件
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
添加实体
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
@TableId(value = "id")
private Long id;
@TableField(value = "name")
private String name;
private Integer age;
private String email;
}
mapper类
@Mapper
public interface UserService extends IService<User> {
}
UserService类
public interface UserService extends IService<User> {
}
UserServiceImpl类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
controller类
@RequestMapping("/mybatisplus")
@Controller
public class MybatisPlusController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
//...
}
使用
mybatis-plus的CRUD实在过于简单,根据名字都能猜个大概,这里不展开说了,这里只举两个简单的例子
@RequestMapping("/deleteByMap")
@ResponseBody
public String deleteByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("age", 23);
map.put("name","张三");
//相当于//DELETE FROM user WHERE name = ? AND age = ?
int i = userMapper.deleteByMap(map);
return String.valueOf(i);
}
@RequestMapping("/updateById")
@ResponseBody
public String updateById(){
User user = new User(5L, "admin", 22, null);
//UPDATE user SET name=?, age=? WHERE id=?
int result = userMapper.updateById(user);
return String.valueOf(result);
}
Wrapper : 条件构造抽象类,最顶端父类
-AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
QueryWrapper : 查询条件封装
UpdateWrapper : Update 条件封装
AbstractLambdaWrapper : 使用Lambda 语法
LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
LambdaUpdateWrapper : Lambda 更新封装Wrapper
QueryWrapper的使用
@RequestMapping("/queryWrapper1")
@ResponseBody
public String queryWrapper1(){
//相当于SELECT id,name,age,email FROM user WHERE (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "a");
wrapper.between("age", 20, 30);
wrapper.isNotNull("email");
List<User> list = userMapper.selectList(wrapper);
return JSON.toJSONString(list);
}
配置类
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
测试类
@RequestMapping("/testPage")
@ResponseBody
public String testPage(){
Page<User> page = new Page<>(1,3);
userMapper.selectPage(page, null);
return JSON.toJSONString(page);
}