栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis-plus

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis-plus

一.基础用法

1.导入pom文件


  com.baomidou
  mybatis-plus-boot-starter
  3.5.1



  org.projectlombok
  lombok



  mysql
  mysql-connector-java
  runtime

2.创建表

CREATE TABLE `user` (
	`id` BIGINT(20) NOT NULL COMMENT '主键ID',
	`name` VARCHAr(30) NULL DEFAULT NULL COMMENT '姓名' COLLATE 'utf8_general_ci',
	`age` INT(11) NULL DEFAULT NULL COMMENT '年龄',
	`email` VARCHAr(50) NULL DEFAULT NULL COMMENT '邮箱' COLLATE 'utf8_general_ci',
	`create_time` DATETIME NULL DEFAULT NULL COMMENT '创建时间',
	`update_time` DATETIME NULL DEFAULT NULL COMMENT '更新时间',
	`version` INT(10) NULL DEFAULT '1' COMMENT '乐观锁',
	`deleted` INT(10) NULL DEFAULT '1' COMMENT '逻辑删除',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

3.配置springboot数据源

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_push?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4.创建实体类

@Data
public class User {

    ///设置id自增
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private Date createTime;
    private Date updateTime;
}

5.配置springboot扫描mapper路径

package com.linfenpeng.mybatispush;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//配置扫描mapper
@MapperScan("com.linfenpeng.mybatispush.mapper")
public class MybatispushApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatispushApplication.class, args);
    }

}

6.测试查询结果(在springboot的test测试)

package com.linfenpeng.mybatispush;

import com.linfenpeng.mybatispush.entity.User;
import com.linfenpeng.mybatispush.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatispushApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
        List users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

}

查询结果

 7.curd接口

//添加
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection entityList);
// 插入(批量)
boolean saveBatch(Collection entityList, int batchSize);

//SaveOrUpdate(保存和添加)

// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList, int batchSize);


删除接口
// 根据 entity 条件,删除记录
boolean remove(Wrapper queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection idList);


更新接口
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList, int batchSize);


Get

// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map getMap(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
 V getObj(Wrapper queryWrapper, Function mapper);

List
// 查询所有
List list();
// 查询列表
List list(Wrapper queryWrapper);
// 查询(根据ID 批量查询)
Collection listByIds(Collection idList);
// 查询(根据 columnMap 条件)
Collection listByMap(Map columnMap);
// 查询所有列表
List> listMaps();
// 查询列表
List> listMaps(Wrapper queryWrapper);
// 查询全部记录
List listObjs();
// 查询全部记录
 List listObjs(Function mapper);
// 根据 Wrapper 条件,查询全部记录
List listObjs(Wrapper queryWrapper);
// 根据 Wrapper 条件,查询全部记录
 List listObjs(Wrapper queryWrapper, Function mapper);

page分页
// 无条件分页查询
IPage page(IPage page);
// 条件分页查询
IPage page(IPage page, Wrapper queryWrapper);
// 无条件分页查询
IPage> pageMaps(IPage page);
// 条件分页查询
IPage> pageMaps(IPage page, Wrapper queryWrapper);

 

二.自动填充

1.在实体类添加注解

@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

注解源码

package com.baomidou.mybatisplus.annotation;

public enum FieldFill {
    DEFAULT,
    INSERT,  
    UPDATE,
    INSERT_UPDATE;

    private FieldFill() {
    }
}

2.编写处理器 


@Slf4j
@Component//将处理器加到‘ioc'容器中
public class MymetaObjectHandler implements metaObjectHandler {
    //插入识别
    @Override
    public void insertFill(metaObject metaObject) {
        log.info("insertFill>>>");
        //String fieldName, Object fieldVal, metaObject metaObject
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
    //跟新识别
    @Override
    public void updateFill(metaObject metaObject) {
        log.info("updateFill>>>");
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
}

备注:setFieldValByName源码

3.编写测试

 @Test
    public void add(){
        User user = new User();
        user.setAge(3);
        user.setEmail("2654994103@qq.com");
        user.setName("linfenpeng");
        userMapper.insert(user);
    }

    @Test
    public void update(){
        User user = new User();
        user.setId(1502540962553253889L);
        user.setAge(3);
        user.setEmail("2654994103@qq.com");
        user.setName("linfenpeng1111");
        userMapper.updateById(user);
    }

测试结果

 三.乐观锁

乐观锁:故名意思十分乐观。它总认为不会出现问题,无论干什么不去上锁!如果出现了问题,再次跟新值测试。

悲观锁:故名意思十分悲观,他总认为总是出现问题,无论干什么都会上锁!再去操作

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

取出记录时,获取当前 version更新时,带上这个 version执行更新时, set version = newVersion where version = oldVersion如果 version 不对,就更新失败

测试MP乐观锁

1.在表加version字段 

 @Version
    private Integer version;

2.配置乐观文件(3.5.1及以后)

package com.linfenpeng.mybatispush.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@EnableTransactionManagement
@Configuration
@MapperScan("com.linfenpeng.mybatispush.mapper") //当springboot没配置mapper扫描路劲可在这配置
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }

}

3.测试

 @Test
    public void testMybatisPlusInterceptor(){
        User user = userMapper.selectById(1502540962553253889L);
        user.setName("linfenpeng");
        userMapper.updateById(user);
    }

    @Test
    public void testMybatisPlusInterceptor1(){
        //线程1
        User user = userMapper.selectById(1502540962553253889L);
        user.setName("linfenpeng111");


        User user2 = userMapper.selectById(1502540962553253889L);
        user.setName("linfenpeng222");
        userMapper.updateById(user2);
        //可用自旋锁
        userMapper.updateById(user);

    }

4.查询语句

@Test
    public void  findList(){
        List users = userMapper.selectBatchIds(Arrays.asList("1", "2"));
        users.forEach(System.out::println);
    }

    @Test
    public void findByField(){
        HashMap userHs = new HashMap<>();
        userHs.put("name","linfenpeng222");
        List users = userMapper.selectByMap(userHs);
        users.forEach(System.out::println);
    }
    @Test
    public void findByFieldLike(){
        QueryWrapper userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name","linfenpeng");
        List users = userMapper.selectList(userQueryWrapper);
        users.forEach(System.out::println);
    }

四.分页

@EnableTransactionManagement
@Configuration
@MapperScan("com.linfenpeng.mybatispush.mapper")
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //开启乐观锁
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //分页配置
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setOverflow(true);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);

        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return mybatisPlusInterceptor;
    }


@Test
    public void testPage(){

        Page userPage = new Page<>(1,4);

        Page userPage1 = userMapper.selectPage(userPage, null);
        long total = userPage1.getTotal();
        System.out.println("total>>>>"+total);
        userPage1.getRecords().forEach(System.out::println);
    }

五.逻辑删除

1.//添加字段
 @TableLogic //逻辑删除
    private Integer deleted;


2.//配置配置文件application.properties
#逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
mybatis-plus.global-config.db-config.logic-delete-value=1 # 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-not-delete-value=0 # 逻辑未删除值(默认为 0)

3.测试
@Test
    public void testDetele(){
        int i = userMapper.deleteById(1L);
        System.out.println("iiii>>>"+i);
    }



六.构造器

@Test
    public void findByFieldLike(){
        QueryWrapper userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name","linfenpeng");
        List users = userMapper.selectList(userQueryWrapper);
        users.forEach(System.out::println);
    }

备注:官方文档条件构造器 | MyBatis-Plus

七.代码生成器

1.pom文件





    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.4
         
    
    com.linfenpeng
    mybatisplusgeneratorcode
    0.0.1-SNAPSHOT
    mybatisplusgeneratorcode
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.0
        

        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        

        
            org.freemarker
            freemarker
            2.3.28
        


        
            org.apache.velocity
            velocity-engine-core
            2.3
        


        
            com.ibeetl
            beetl
            3.10.0.RELEASE
        


        
            io.springfox
            springfox-swagger2
            2.7.0
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        




        
        
            org.projectlombok
            lombok
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


 2.代码生成器

package com.linfenpeng.mybatisplusgeneratorcode;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;



public class LinfenpengGeneratorCode {
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("linfenpeng");
        gc.setOpen(false);
        gc.setFileOverride(true); //是否覆盖
        gc.setServiceName("%sService");
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis_push?characterEncoding=utf-8&useSSL=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("mybatisplusgeneratorcodeTest");
        pc.setParent("com.linfenpeng.mybatisplusgeneratorcode");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //映射表ming
        //strategy.setInclude("user","bolg");
        strategy.setInclude("user");

        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        //Rest风格
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true); //127.0.0.1:8080/hello_id_1
        //设置逻辑删除
        strategy.setLogicDeleteFieldName("deleted");
        //自动填充配置
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time",FieldFill.INSERT_UPDATE);
        ArrayList fillList = new ArrayList<>();
        fillList.add(createTime);
        fillList.add(updateTime);
        strategy.setTableFillList(fillList);

        //乐观锁
        strategy.setVersionFieldName("version");


        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
















转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号