mybatisplus简单入门

xml

 
	<dependency>
	    <groupId>com.baomidougroupId>
	    <artifactId>mybatis-plus-boot-starterartifactId>
	    <version>3.3.1.tmpversion>
	dependency>
	 
	<dependency>
	    <groupId>com.baomidougroupId>
	    <artifactId>mybatis-plus-generatorartifactId>
	    <version>3.3.1.tmpversion>
	dependency>
	 
	        <dependency>
	            <groupId>org.freemarkergroupId>
	            <artifactId>freemarkerartifactId>
	            <version>2.3.30version>
	        dependency>
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
# 日志显示
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

CodeGenerator.java

public class CodeGenerator {
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
      throw new MybatisPlusException("请输入正确的"+tip+"!");
    }
    public static void main(String[] args) {
        //代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //当前路径
        String projectPath = System.getProperty("user.dir");
        gc.setAuthor("ray");
        gc.setOutputDir(projectPath + "/src/main/java");
        //%s 为占位符 UserService 去掉默认生成IUserService
        gc.setServiceName("%sService");
        //生成之后是否打开资源管理器
        gc.setOpen(false);
        //开启实体属性 Swagger2 注解
//        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ray_fast?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("");
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
        //模块名
        pc.setModuleName(null);
        pc.setParent("com.ray.mybatisplus");
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        //自定义配置
//        InjectionConfig cfg = ()
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 xxMapper.xml
                return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        //配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        //配置策略
        StrategyConfig strategy = new StrategyConfig();
        //下划线转驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //entity继承BaseEntity
//        strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity");
        //添加Lombok
        strategy.setEntityLombokModel(true);
        //生成的表
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        //去掉前缀
        strategy.setTablePrefix("sys_");
        mpg.setStrategy(strategy);
        //设置为 FreemarkerTemplate
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 执行生成
        mpg.execute();
    }
}

/********************************************************************************/

mybatisplus简单入门_第1张图片

分页

   public Page<BsCompany> getCompanyList(PageGrid<CompanyPageParam> param) {
        Page<BsCompany> page = new Page<>(param.getPageNo(), param.getPageSize());
        QueryWrapper<BsCompany> wrapper = new QueryWrapper<>();
        wrapper.eq("is_active", "1");
        if(StringUtils.isNotEmpty(param.getParameter().getCompanyName())){
            wrapper.like("company_name", param.getParameter().getCompanyName());
        }
        if(param.getParameter().getCompanyArea()!=null){
            wrapper.eq("company_area_id",param.getParameter().getCompanyArea());
        }
        return baseMapper.selectPage(page, wrapper);
    }
    
    /**
     * 分页获取巡检列表
     * @param param
     * @return
     */
    @Override
    public Page<CheckRecordVo> getCheckRecordList(PageGrid<IdParam> param) {
        Page page = new Page<>(param.getPageNo(), param.getPageSize());
        QueryWrapper<CheckRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("check_company", param.getParameter().getId());
        wrapper.ne("is_active", 0);
        wrapper.orderByDesc("create_time");
        checkRecordService.page(page, wrapper);
        List<CheckRecordVo> vos = new ArrayList<>();
        for (Object record : page.getRecords()) {
            CheckRecord checkRecord = (CheckRecord)record;
            CheckRecordVo vo = new CheckRecordVo();
            vo.setCheckState(checkRecord.getCheckState());
            vo.setCheckUser(checkRecord.getCheckUser());
            vo.setCheckDate(checkRecord.getCheckDate());
            vos.add(vo);
        }
        page.setRecords(vos);
        return page;
    }

查询

@SpringBootTest
class MybatisplusApplicationTests {
    @test
    public void test(){
    
    }
}
//mapper.selectList(null);
QueryWrapper wrapper = new QueryWrapper();
//        Map map = new HashMap<>();
//        map.put("name","小红");
//        map.put("age",3);
//        wrapper.allEq(map);
//        wrapper.gt("age",2);
//        wrapper.ne("name","小红");
//        wrapper.ge("age",2);

//like '%小'
//        wrapper.likeLeft("name","小");
//like '小%'
//        wrapper.likeRight("name","小");

//inSQL
//        wrapper.inSql("id","select id from user where id < 10");
//        wrapper.inSql("age","select age from user where age > 3");
//        wrapper.orderByDesc("age");

//        wrapper.orderByAsc("age");
//        wrapper.having("id > 8");
mapper.selectList(wrapper).forEach(System.out::println);

//        System.out.println(mapper.selectById(7));
//        mapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);

//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
//        Map map = new HashMap<>();
//        map.put("id",7);
//        mapper.selectByMap(map).forEach(System.out::println);

QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
        System.out.println(mapper.selectCount(wrapper));
//
//        //将查询的结果集封装到Map中
//        mapper.selectMaps(wrapper).forEach(System.out::println);
//        System.out.println("-------------------");
//        mapper.selectList(wrapper).forEach(System.out::println);

//分页查询
//        Page page = new Page<>(2,2);
//        Page result = mapper.selectPage(page,null);
//        System.out.println(result.getSize());
//        System.out.println(result.getTotal());
//        result.getRecords().forEach(System.out::println);

//        Page> page = new Page<>(1,2);
//        mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);

//        mapper.selectObjs(null).forEach(System.out::println);


System.out.println(mapper.selectOne(wrapper));

自定义 SQL(多表关联查询)

package com.southwind.mybatisplus.entity;
import lombok.Data;
@Data
public class ProductVO {
    private Integer category;
    private Integer count;
    private String description;
    private Integer userId;
    private String userName;
}
public interface UserMapper extends BaseMapper<User> {
    @Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")
    List<ProductVO> productList(Integer id);
}

添加

User user = new User();
user.setTitle("小明");
user.setAge(22);
mapper.insert(user);
System.out.println(user);

删除

//mapper.deleteById(1);
//        mapper.deleteBatchIds(Arrays.asList(7,8));
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("age",14);
//        mapper.delete(wrapper);

Map<String,Object> map = new HashMap<>();
map.put("id",10);
mapper.deleteByMap(map);

修改

//        //update ... version = 3 where version = 2
//        User user = mapper.selectById(7);
//        user.setTitle("一号");

//        //update ... version = 3 where version = 2
//        User user1 = mapper.selectById(7);
//        user1.setTitle("二号");
//
//        mapper.updateById(user1);
//        mapper.updateById(user);

User user = mapper.selectById(1);
user.setTitle("小红");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",22);
mapper.update(user,wrapper);

/************************************************************/

@TableId

设置主键映射,value 映射主键字段名

type 设置主键类型,主键的生成策略,

AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
描述
AUTO 数据库自增
NONE MP set 主键,雪花算法实现
INPUT 需要开发者手动赋值
ASSIGN_ID MP 分配 ID,Long、Integer、String
ASSIGN_UUID 分配 UUID,Strinig

@TableField

映射非主键字段,value 映射字段名
exist 表示是否为数据库字段 false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用 exist,VO、DTO
select 表示是否查询该字段
fill 表示是否自动填充,将对象存入数据库的时候,由 MyBatis Plus 自动给某些字段赋值,create_time、update_time
1、给表添加 create_time、update_time 字段
2、实体类中添加成员变量

@Data
@TableName(value = "user")
public class User {
    @TableId
    private String id;
    @TableField(value = "name",select = false)
    private String title;
    private Integer age;
    @TableField(exist = false)
    private String gender;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

3、创建自动填充处理器
createTime 和 createTime

package com.southwind.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

@Version

标记乐观锁,通过 version 字段来保证数据的安全性,当修改数据的时候,会以 version 作为条件,当条件成立的时候才会修改成功。

version = 2

线程 1:update … set version = 2 where version = 1

线程2 :update … set version = 2 where version = 1

1、数据库表添加 version 字段,默认值为 1

2、实体类添加 version 成员变量,并且添加 @Version

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.util.Date;

@Data
@TableName(value = "user")
public class User {
    @TableId
    private String id;
    @TableField(value = "name",select = false)
    private String title;
    private Integer age;
    @TableField(exist = false)
    private String gender;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @Version
    private Integer version;
}

3、注册配置类

package com.southwind.mybatisplus.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
    
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
    
}

@TableLogic

映射逻辑删除

1、数据表添加 deleted 字段

2、实体类添加注解

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.southwind.mybatisplus.enums.AgeEnum;
import com.southwind.mybatisplus.enums.StatusEnum;
import lombok.Data;

import java.util.Date;

@Data
@TableName(value = "user")
public class User {
    @TableId
    private String id;
    @TableField(value = "name",select = false)
    private String title;
    private AgeEnum age;
    @TableField(exist = false)
    private String gender;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @Version
    private Integer version;
    @TableField(value = "status")
    private StatusEnum statusEnum;
    @TableLogic
    private Integer deleted;
}

3、application.yml 添加配置

global-config:
  db-config:
    logic-not-delete-value: 0
    logic-delete-value: 1

你可能感兴趣的:(java,mybatis,数据库)