赞
踩
目录
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
划重点:mybaits-plus是对mybatis的增强,在mybatis-plus中也可以使用mybatis的功能
一般看官网就可以看懂,这个框架是国人开发的
- CREATE TABLE user
- (
- id BIGINT(20) NOT NULL COMMENT '主键ID',
- name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
- age INT(11) NULL DEFAULT NULL COMMENT '年龄',
- email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
- create_time date NULL DEFAULT NULL COMMENT '创建时间',
- update_time date NULL DEFAULT NULL COMMENT '修改时间',
- PRIMARY KEY (id)
- );
- INSERT INTO user (id, name, age, email) VALUES
- (1, 'Jone', 18, 'test1@baomidou.com'),
- (2, 'Jack', 20, 'test2@baomidou.com'),
- (3, 'Tom', 28, 'test3@baomidou.com'),
- (4, 'Sandy', 21, 'test4@baomidou.com'),
- (5, 'Billie', 24, 'test5@baomidou.com');
- <dependencies>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </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.1</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
-
- </dependencies>
- spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/dubbotest?serverTimezone=UTC
- username: root
- password: root
- logging:
- level:
- root: info
- com.sofwin: debug
- mybatis-plus:
- configuration:
- #打印sql语句
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- package com.sofwin;
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- @SpringBootApplication
- @MapperScan(basePackages = "com.sofwin.mapper")
- public class App {
- public static void main(String[]args){
- SpringApplication.run(App.class,args);
- }
- }
- package com.sofwin.pojo;
-
- import com.baomidou.mybatisplus.annotation.*;
- import lombok.Data;
-
- import java.util.Date;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- //查看方法的快捷键 alt +7
- @Data
- //表名注解,标识实体类中对应的表 使用位置实体类
- //value 表名
- @TableName(value = "user")
- public class User {
- //标识id为表的主键
- //value为id的名称 type为主键自增情况
- //auto为数据库自增
- //ASSIGN_UUID 通过uuid进行主键的自增
- @TableId(value = "id",type = IdType.AUTO)
- private Long id;
- @TableField("name") //非主键的字段描述
- private String name;
- private Integer age;
- private String email;
- private String realName;
- //insert的时候触发的时候自动填充
- @TableField(fill = FieldFill.INSERT)
- private Date createTime;
- //update触发的时候自动填充
- @TableField(fill = FieldFill.UPDATE)
- private Date updateTime;
-
-
- }
- package com.sofwin.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.sofwin.pojo.User;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- public interface UserMapper extends BaseMapper<User> {
- }
service实现BashMapper接口 这个接口中由mybatis-plus对单表增删改查的封装
- package com.sofwin.test;
-
- import com.baomidou.mybatisplus.core.conditions.Wrapper;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Constants;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.sofwin.mapper.UserMapper;
- import com.sofwin.pojo.User;
- import org.apache.ibatis.annotations.Param;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import javax.xml.transform.Source;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
-
- import static javafx.scene.input.KeyCode.T;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- @SpringBootTest
- public class MybatisPlusTest {
- @Autowired
- private UserMapper mapper;
-
- //继承 BashMapper的接口的方法
-
- @Test
- public void testList(){
- IPage<User> page =new Page<User>(1,10);
- page= mapper.selectPage(page,null);
- List<User> records = page.getRecords();
- }
- @Test
- public void test01(){
- // 1.根据 ID 查询
- User user = mapper.selectById(1L);
- System.out.println("根据ID查询 "+user);
- // 2.根据 entity 条件,查询一条记录 ,查询出现多个数据的话会出错
- QueryWrapper<User> queryWrapper=new QueryWrapper<User>();
- //第一个参数的表的字段名
- queryWrapper.like("real_Name","xiao").
- eq("age",20);
- User user1 = mapper.selectOne(queryWrapper);
- System.out.println("根据条件继续查询"+user1);
- // 3.查询(根据ID 批量查询)
- List list=new ArrayList();
- list.add(1);
- list.add(2);
- list.add(3);
- list.add(4);
- List<User> list1 = mapper.selectBatchIds(list);
- System.out.println("通过id集合查询多条数据 "+list1);
- // 4.根据 entity 条件,查询全部记录
- QueryWrapper<User> queryWrapper1=new QueryWrapper<User>();
- //第一个参数的表的字段名
- queryWrapper.like("real_Name","xiao");
- List<User> list2 = mapper.selectList(queryWrapper1);
- System.out.println("通过条件查询多条数据 "+list2);
- // 5.根据 Wrapper 条件,查询总记录数
- Long aLong = mapper.selectCount(queryWrapper1);
- System.out.println("通过Wrapper条件,查询总记录数 "+aLong);
- //分页通过pagehelper进行分页
- }
- //新增
- @Test
- public void test02(){
- User user=new User();
- user.setName("wwwttt111");
- int insert = mapper.insert(user);
- }
- //删除
- @Test
- public void test03(){
- //通过id删除
- // int i = mapper.deleteById(6);
- //批量删除
- Integer [] ids={7,8,9,10};
- //批量删除传入的是集合
- mapper.deleteBatchIds(Arrays.asList(ids));
- }
-
- //修改
- @Test
- public void test04(){
- //通过id进行修改
- User user=new User();
- user.setId(11L);
- user.setName("zhangsna");
- user.setAge(11);
- user.setEmail("100@11");
- int i = mapper.updateById(user);
- }
- @Test
- public void test05(){
- //通过条件进行修改 ---利用条件构造器
- User user=new User();
-
- user.setName("zhangsnaplus11");
- //条件构造器
- UpdateWrapper<User> userWrapper=new UpdateWrapper<User>();
- userWrapper.eq("id","2");
- // LambdaQueryWrapper的类型
- // LambdaQueryWrapper<User> lambdaQueryWrapper =new LambdaQueryWrapper<User>();
- // lambdaQueryWrapper.eq(User::getRealName,"zhang");
- int i = mapper.update(user,userWrapper);
- }
-
- }
注意:mybatis-plus的分页要写一个拦截器才能产生作用
- package com.sofwin.config;
-
- 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;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- //mybatis plus的插件的拦截器
- @Configuration
- public class PageInteceptor {
-
- @Bean
- public MybatisPlusInterceptor getPageInteceptor(){
- MybatisPlusInterceptor pageInteceptor= new MybatisPlusInterceptor();
- pageInteceptor.addInnerInterceptor(new PaginationInnerInterceptor());
- return pageInteceptor;
- }
- }
- @Test
- public void testPage() {
- //第一页 每页显示3条数据的page对象
- Page<User> page = new Page<>(1,3);
- Page<User> userPages = userMapper.selectPage(page, null);
- long pages = userPages.getPages();//总页数
- System.out.println(pages);
- long current = userPages.getCurrent();//当前页
- System.out.println(current);
- List<User> records = userPages.getRecords(); //查询数据集合
- System.out.println(records);
- long total = userPages.getTotal();//总记录数
- System.out.println(total);
- boolean hasNext = userPages.hasNext();//是否有下一页
- System.out.println(hasNext);
- boolean hasPrevious = userPages.hasPrevious();//是否有上一页
- System.out.println(hasPrevious);
- }
注意:mybatis-plus的还有一个功能是在新增和修改的时候自动添加时间
1.我们要在pojo中设置
2.写一个类实现 MetaObjectHandler接口
- package com.sofwin.handler;
-
- import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
- import org.apache.ibatis.reflection.MetaObject;
- import org.springframework.stereotype.Component;
-
- import java.util.Date;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- //当新增或者修改的时候自动添加时间
- @Component
- public class DateHander implements MetaObjectHandler {
- @Override
- public void insertFill(MetaObject metaObject) {
- this.strictInsertFill(metaObject,"createTime",Date.class,new Date());
- }
-
- @Override
- public void updateFill(MetaObject metaObject) {
- this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
- }
- }
实现IService接口
- package com.sofwin.service;
-
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.sofwin.pojo.User;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- public interface UserService extends IService<User> {
- }
实现userservice接口继承ServiceImpl<M,T>
M代表的mapper T代表实体类
- package com.sofwin.service.impl;
-
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.sofwin.mapper.UserMapper;
- import com.sofwin.pojo.User;
- import com.sofwin.service.UserService;
- import org.springframework.stereotype.Service;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- @Service
- //第一个泛型是mapper的 第一个是实体类的
- public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
-
- }
- package com.sofwin.test;
-
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.sofwin.pojo.User;
- import com.sofwin.service.UserService;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- @SpringBootTest
- public class ServiceTest {
- @Autowired
- private UserService userService;
- @Test
- public void test(){
- LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
- lambdaQueryWrapper.eq(User::getName,"wwwttt")
- ;
- //eq 等于 nq不等于
- //gt 大于 ge 大于等于 lt小于 le小于等于
- // .or().进行拼接 正常. 接着. 是and
- userService.getOne(lambdaQueryWrapper);
- }
-
- }
接口的具体方法官网:CRUD 接口 | MyBatis-Plus
我使用的新版的版本要大于等于3.5.1
- <dependencies>
- <!-- 代码生成器 -->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-generator</artifactId>
- <version>3.5.3</version>
- </dependency>
-
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.5.2</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-freemarker</artifactId>
- </dependency>
- <!--文档框架 swagger 要跟springboot的低版本兼容 2.4.8-->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-boot-starter</artifactId>
- <version>3.0.0</version>
- </dependency>
- </dependencies>
- server:
- port: 80
- spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/dubbotest?serverTimezone=UTC
- username: root
- password: root
- package com.sofwin.controller;
-
-
- import com.baomidou.mybatisplus.generator.FastAutoGenerator;
- import com.baomidou.mybatisplus.generator.config.OutputFile;
- import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.Mapping;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.RestController;
-
- import java.io.OutputStream;
- import java.util.Collections;
-
- /**
- * <p>
- * 前端控制器
- * </p>
- *
- * @author wentao
- * @since 2022-08-24
- */
- @RestController
- public class GeneratorController {
- @GetMapping("/gen")
- public String test(){
- //url是数据库的url 账户 密码
- FastAutoGenerator.create("jdbc:mysql://localhost:3306/dubbotest?serverTimezone=UTC", "root", "root")
- .globalConfig(builder -> {
- builder.author("wentao") // 设置作者
- .enableSwagger() // 开启 swagger 模式
- .fileOverride() // 覆盖已生成文件
- .outputDir("D://mybatisplus-generator"); // 指定输出目录
- })
- .packageConfig(builder -> {
- builder.parent("com.sofwin") // 设置父包名
- .moduleName("system") // 设置父包模块名
- .pathInfo(Collections.singletonMap(OutputFile.xml, "D://mybatisplus-generator")); // 设置mapperXml生成路径
- })
- .strategyConfig(builder -> {
- builder.addInclude("user") ;// 设置需要生成的表名
- // .addTablePrefix("t_", "c_"); // 设置过滤表前缀
- })
- .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
- .execute();
-
- return "ok";
- }
- }
-
- package com.sofwin;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- @SpringBootApplication
- @EnableSwagger2
- public class App {
- public static void main(String[]args){
- SpringApplication.run(App.class,args);
- }
- }
启动访问即可生成
导入依赖
- <!--监控sql的执行-->
- <dependency>
- <groupId>p6spy</groupId>
- <artifactId>p6spy</artifactId>
- <version>3.9.1</version>
- </dependency>
配置yml
- spring:
- datasource:
- driver-class-name: com.p6spy.engine.spy.P6SpyDriver
- url: jdbc:p6spy:mysql://localhost:3306/dubbotest?serverTimezone=UTC
- username: root
- password: root
只能照着之前的dataSource的稍微改一下即可
spy.properties
#3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory #3.2.1以下使用或者不配置 #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定义日志打印 logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger #日志输出到控制台 appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger # 使用日志系统记录 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 设置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前缀 useprefix=true # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 实际驱动可多个 #driverlist=org.h2.Driver # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准 2 秒 outagedetectioninterval=2
执行的时候就会出现
代表成功
一般在企业中,我们进行删除,不是一般会设置一个字段,例如规定0位正常 1位删除,一般删除是进行修改,如果不使用逻辑删除,就是看着比较别扭,但是也是可以实现的,这里mybatis-plus给我们提供了这个逻辑删除的功能
设置yml
- #逻辑删除
- global-config:
- db-config:
- logic-delete-field: status # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
- logic-delete-value: 1 # 逻辑已删除值(默认为 1)
- logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
设置pojo的属性
- package com.sofwin.pojo;
-
- import com.baomidou.mybatisplus.annotation.*;
- import lombok.Data;
-
- import java.util.Date;
-
- /**
- * @author : wentao
- * @version : 1.0
- */
- //查看方法的快捷键 alt +7
- @Data
- //表名注解,标识实体类中对应的表 使用位置实体类
- //value 表名
- @TableName(value = "user")
- public class User {
- //标识id为表的主键
- //value为id的名称 type为主键自增情况
- //auto为数据库自增
- //ASSIGN_UUID 通过uuid进行主键的自增
- @TableId(value = "id",type = IdType.AUTO)
- private Long id;
- @TableField("name") //非主键的字段描述
- private String name;
- private Integer age;
- private String email;
- private String realName;
- //insert的时候触发的时候自动填充
- @TableField(fill = FieldFill.INSERT)
- private Date createTime;
- //update触发的时候自动填充
- @TableField(fill = FieldFill.UPDATE)
- private Date updateTime;
- //乐观锁的 要设置默认为1
- @Version
- private Integer version;
- @TableLogic
- private Integer status;
- }
测试
- @Test
- public void test03(){
- //通过id删除
- mapper.deleteById(14);
-
- // mapper.deleteBatchIds(Arrays.asList(ids));
- }
执行delete其实执行的就是修改
当要更新一条记录的时候,希望这条记录没有被别人更新乐观锁实现方式
添加bean对象
- @Bean
- public MybatisPlusInterceptor mybatisPlusInterceptor() {
- MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
- interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
- return interceptor;
- }
在pojo中
- @Version
- private Integer version;
注意:version这个字段一定要设置默认值为1、
- //乐观锁 一般都是先进行查找 然后进行设置
- @Test
- public void test14(){
- //通过id进行修改
- User user = mapper.selectById(11);
- user.setAge(10);
- User user1 = mapper.selectById(11);
- user1.setAge(20);
-
- mapper.updateById(user);
- mapper.updateById(user1);
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。