spring boot + mybatis plus

1.spring boot 环境搭建

1.添加mven依赖包

        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        
        
        
            junit
            junit
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.0
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

2.添加 application.yml 配置(resources 目录下)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

#Servlet容器配置
server:
  port: 80
  servlet:
    context-path: /index

#配置日志
logging:
  level:
    root: warn
    com.zimug.boot.launch.mapper: trace

2.mybatis-plus 环境搭建

添加mapper 扫描 注:@MapperScan("自己mapper的路径地址")

@SpringBootApplication
@MapperScan("com.example.my.app.user.mapper")
public class MyApplication {

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

}

(1).添加

Mapper.insert(bean);

(2).修改

Bean user2 = Mapper.selectById(1);
user2.setTitle("test");
int result = Mapper.updateById(user2);

(3).删除

//更据id进行删除
int rows = userMapper.deleteById(1);
System.out.println("影响记录数:" + rows);
//构造条件
Map map = new HashMap<>();
map.put("name","字母哥");
map.put("age",18);
//执行删除
int rows = userMapper.deleteByMap(map);
System.out.println("影响记录数:" + rows);

(4).查询

//根据主键查询一条数据
User user = userMapper.selectById(1);
System.out.println(user);
//根据ids批量查找数据
List ids = Arrays.asList(
    1,
    2,
    3
);
List list = userMapper.selectBatchIds(ids);
list.forEach(System.out::println);

3.mybatis-plus 代码自动生成器

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 此类为mybatis-plus的数据库表模板生成器
 */
public class CodeGenerator {
    public static final String package_name = "com.example.my.app"; //设置生成代码路径
    public static final String super_controller = "com.example.my.base.BaseController"; //你自己的父类实体,没有就不用设置!
    public static final String super_entity = "com.example.my.base.BaseEntity"; //"你自己的父类实体,没有就不用设置!"

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        String projectPath = System.getProperty("user.dir");
        /*全局配置 GlobalConfig*/
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("jobob");
        globalConfig.setOpen(false);
        mpg.setGlobalConfig(globalConfig);
        /*数据源配置 DataSourceConfig*/
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("root");
        mpg.setDataSource(dataSourceConfig);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(package_name); /*设置引入的包*/
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // 什么都不做
            }
        };
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义输出配置
        List focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + 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);
        strategy.setSuperEntityClass(super_entity);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass(super_controller);
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 读取控制台内容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

}

你可能感兴趣的:(spring boot + mybatis plus)