mybatis plus

此网站中含有 mp的相关配置

    快速开始 | MyBatis-Plus  

1、 mp的crud

(1)添加

在实体类中为主键id添加自动注入,这样就会在数据库中自动生成id

注意:一定要将数据库id这一列设为自增

 /**
     *  主键mp提供相应的生成策略:
     *     AUTO(0),递增策略,如果使用该策略必须要求数据表的列也是递增。
     *     NONE(1),
     *     INPUT(2),没有策略,必须人为的输入id值
     *     ASSIGN_ID(3), 随机生成一个Long类型的值。该值一定是唯一。而且每次生成都不会相同。算法:雪花算法。 适合分布式主键。
     *     ASSIGN_UUID(4); 随机产生一个String类型的值。该值也是唯一的。
     */
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("孙悟空");
        user.setAge(18);
        user.setEmail("230234345070@qq.com");
        System.out.println("添加前:============"+user);
        int insert = userMapper.insert(user); //mp会把生成的主键值复制给对象。
        System.out.println("添加后:============"+user);
        System.out.println(insert);
    }

(2)删除

在数据库中新增isdelete这一逻辑列,可以为其设置默认值,这样就不用写相关的配置类了

在实体类也要增加这一成员变量

   /**
     *  实际开发中: 我们的删除可能是逻辑删除。所谓的逻辑删除就是修改功能。把某个列修改以删除的状态值。
     *  只对自动注入的 sql 起效:
             * 插入: 不作限制---
             * 查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
             * 更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
             * 删除: 转变为 更新
     * (1)增加一个逻辑字段: isdeleted  0表示未删除 1表示删除.
     * (2)实体类上的字段添加   @TableLogic.
     */
    @Test
    public void testDelete(){
        //根据主键删除
        int i = userMapper.deleteById(1551469383089573889L);
        System.out.println(i);
    }

(3)修改

 /**
     *   自动填充功能:
     *     在阿里规则中我们的每一张表必须具备的三个字段 id,create_time,update_time.
     *     这两个字段要不要自己添加。
     *
     *    (1)在需要自动填充属性上@TableField(fill=)
     *    (2)创建mp自动填充类
     */
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(2L);
        user.setName("张学友");
        //根据主键进行修改
        int i = userMapper.updateById(user);
        System.out.println(i);
    }

配置类:

@Slf4j
@Component

public class MyMetaObjectHandler implements MetaObjectHandler {

    //当添加时自动填充的值
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 或者
        this.strictInsertFill(metaObject, "gmtCreate", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "isdeleted", ()->0, Integer.class); // 起始版本 3.3.3(推荐)
         // 起始版本 3.3.3(推荐)
    }
    //当修改时自动填充的值
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 或者
        this.strictUpdateFill(metaObject, "gmtUpdate", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
    }
}

(4)查询

 @Test
    public void testSelectByCondition(){
        //Wrapper:封装了关于查询的各种条件方法。有三个子类最常用: QueryWrapper查询条件  UpdateWrapper修改条件  LambdaQueryWrapper查询使用lambda表达式条件
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.between("age", 15, 25);
        wrapper.select("name","age");
        wrapper.like("name","a");
        System.out.println(userMapper.selectList(wrapper));

    }

(5)分页查询

 

2、代码自动生成器

2.1、代码自动生成(新)

(1)依赖

<!--代码自动生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

(2)自动生成代码

package com.wk;

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 Geneator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/shiro_permission?serverTimezone=Asia/Shanghai", "root", "123456de")
                .globalConfig(builder -> {
                    builder.author("wk") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir(".\\src\\main\\java\\"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.wk") // 设置父包名
                            .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "src\\main\\resources\\mapper\\")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("acl_user","acl_role","acl_permission")// 设置需要生成的表名
                            .addTablePrefix("acl_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }
}

2.2、代码生成器(旧)

(1)依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

(2)生成代码

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String property = System.getProperty("user.dir");
        gc.setOutputDir(property+"/src/main/java");
        gc.setAuthor("wk");
        gc.setOpen(false);
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mys1?serverTimezone=Asia/Shanghai");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456de");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("system");
        pc.setParent("com.wk");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 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) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return  "./src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user","dept");
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        // 写于父类中的公共字段
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值