入门篇
- 1.快速入门
- 1.1数据库准备
- 1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程
- 1.3编写DataSource相关配置(配置MySQL数据库连接)
- 1.4编码
- 1.5测试
- 2.使用MybatisPlus完成增删改
- 2.1Mapper添加
- 2.2Mapper删除
- 2.3Mapper修改
- 3.使用MybatisPlus完成查询
- 4.Service封装
- 5.逆向工程-代码生成器
1.快速入门
1.1数据库准备
现有一张tb_user表,其表结构如下:
对应的数据库脚本如下:
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybatisplus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisplus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.3编写DataSource相关配置(配置MySQL数据库连接)
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
1.4编码
实体类
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("tb_user")
@Data
public class User {
private Integer id;
private String username;
private String password;
private String name;
private Integer age;
private String email;
}
其中@TableName是MybatisPlus注解,内容对应MySQL表名称,@Data是Lombok的注解,该注解的主要功能是省去了getter/setter方法。
编写mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.domain.User;
public interface UserMapper extends BaseMapper<User> {
}
启动类增加@MapperScan注解
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mybatisplus")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
1.5测试
import com.example.mybatisplus.domain.User;
import com.example.mybatisplus.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MybatisplusApplication.class)
@RunWith(SpringRunner.class)
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void test01(){
User user = userMapper.selectById(1);
System.out.println(user);
}
}
@Test需引入Junit依赖包,可以从https://mvnrepository.com/下载
2.使用MybatisPlus完成增删改
2.1Mapper添加
方法:
//添加一条记录 参数:T 实体对象
int insert(T entity);
测试:
@Test
public void testInsert(){
User user=new User();
user.setUsername("xy");
user.setPassword("123456");
user.setName("专精装项羽");
user.setAge(180);
int count = userMapper.insert(user);
System.out.println(count);
}
2.2Mapper删除
方法:
//根据ID删除
int deleteById(Serializable id);
//根据实体类删除
int deleteById(T entity);
//根据columnMap条件删除
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
//根据entiy条件,删除记录
int delete(@Param("ew") Wrapper<T> queryWrapper);
//根据ID批量删除
int deleteBatchIds(@Param("coll") Collection<?> idList);
测试:
根据id删除
@Test
public void testDelete01(){
int count=userMapper.deleteById(1883332609);
}
根据id批量删除
@Test
public void testDelete02(){
List list=new ArrayList();
list.add(3);
list.add(4);
int count = userMapper.deleteBatchIds(list);
}
根据map构造条件,删除
@Test
public void testDelete03(){
Map<String,Object> map=new HashMap<>();
map.put("username","dg");
map.put("name","呆瓜");
int count = userMapper.deleteByMap(map);
}
2.3Mapper修改
方法:
//根据ID修改
int updateById(@Param("et") T entity);
//根据whereEntiy条件修改
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
测试:
@Test
public void testUpdate01(){
User user=new User();
user.setId(3);
user.setName("杨杨杨");
int count = userMapper.updateById(user);
}
@Test
public void testUpdate02(){
User user=new User();
user.setName("旺旺旺");
QueryWrapper<User> qw=new QueryWrapper<>();
qw.eq("id",1);
int count = userMapper.update(user,qw);
}
3.使用MybatisPlus完成查询
查询的方法比较多,所以单独总结一起
//根据ID查询,查询出一条记录
T selectById(Serializable id);
//根据ID批量查询,查询出多条记录
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
//根据entity条件,查询出多条记录
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
//根据columnMap条件,查询出多条记录
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
//根据queryWrapper条件,查询出多条记录
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
//根据queryWrapper条件,查询出多条记录(注意:只返回第一个字段的值)
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
//根据entiy条件,查询出多条记录并分页
<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
//根据Wrapper条件,查询出多条记录并分页
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
分页查询
配置拦截器
@Configuration
public class PageConfig {
/**
* 3.4.0之前的版本用这个
* @return
*/
/* @Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}*/
/**
* 3.4.0之后提供的拦截器的配置方式
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
查询
@Test
public void testSelectPage(){
int current=1;//当前页码
int size=5;//每页显示条数
IPage<User> page=new Page(current,size);
userMapper.selectPage(page,null);
List<User> records = page.getRecords();//当前页的数据
long pages = page.getPages();//总页数
long total = page.getTotal();//总记录数
System.out.println(records);
System.out.println(pages);
System.out.println(total);
}
条件构造器查询
Wrapper:
1.QueryWrapper 查询
LambdaQueryWrapper (支持Lambda表达式)
2.UpdateWrapper 更新
LamdbaUpdateWrapper(支持Lamdba表达式)
基础查询
通过QueryWrapper指定查询条件
sql:select * from tb_user where password='123456' and age>18
eq():等于=
ne():不等于=
gt():大于>
ge():大于等于>=
lt():小于<
le():小于等于<=
between(): BETWEEN 值1 AND 值2
in():in
notIn():not in
@Test
public void testWrapper1(){
//创建查询条件构造器
QueryWrapper<User> wrapper=new QueryWrapper<>();
//设置条件
wrapper.eq("username","bq")
.lt("age",23)
.in("name","白起","旺旺旺");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
以上sql等同于 select * from tb_user where username=“bq” and age<23 and name in(“白起”,“旺旺旺”)
逻辑查询or
or():让紧接着下一个方法用or连接
@Test
public void testWrapper2(){
//创建查询条件构造器
QueryWrapper<User> wrapper=new QueryWrapper<>();
//设置条件
wrapper.eq("username","bq")
.or()
.lt("age",23)
.in("name","王昭君","旺旺旺");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
模糊查询like
like //模糊查询匹配值‘%值%’
notLike //模糊查询不匹配值‘%值%’
likeLeft //模糊查询匹配最后一位值‘%值’
likeRight //模糊查询匹配第一位值‘值%’
@Test
public void testWrapper3(){
//创建查询条件构造器
QueryWrapper<User> wrapper=new QueryWrapper<>();
//设置条件
wrapper.likeLeft("name","君");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
排序查询
orderBy
orderByAsc
orderByDESC
select:指定需要查询的字段
@Test
public void testWrapper4(){
//创建查询条件构造器
QueryWrapper<User> wrapper=new QueryWrapper<>();
//设置条件
wrapper.lt("age",22).select("age");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
4.Service封装
MVC架构
controller---->service(impl)------->dao(mapper)
Mybatis-Plus 为了开发更加快捷,对业务层也进行了封装,直接提供了相关的接口和实现类。我们在进行业务层开发时,可以继承它提供的接口和实现类,使得编码更加高效
-
- 定义接口继承IService
-
- 定义实现类继承ServiceImpl<Mapper,Entity> 实现定义的接口
接口
public interface _UserService extends IService<User> {
}
实现类实现接口
@Service
public class _UserServiceImpl extends ServiceImpl<UserMapper, User> implements _UserService {}
测试
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mybatisplustest.MybatisPlusTestApplication;
import com.example.mybatisplustest.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MybatisPlusTestApplication.class)
@RunWith(SpringRunner.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testFind(){
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("id",1);
User one = userService.getOne(wrapper);
System.out.println(one);
}
}
5.逆向工程-代码生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
安装
引入坐标依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
package com.example.mybatisplus;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.Collections;
public class Generator {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "123456")
.globalConfig(builder -> {
builder.author("test") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D://"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
.moduleName("system") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("tb_user") // 设置需要生成的表名
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
生成结果