mybatis-plus笔记

为什么要学它?MyBatisPlus可以节省我们大量的时间,所有CRUD代码都可以自动完成

官网:https://baomidou.com/(大部分内容参考官方文档,笔记只记录文档没有提到的)

project位置:workspace/mybatis_plus


1、快速开始

说明:不要同时导入mybatis和mybatis-plus的依赖,因为可能存在配置上冲突的问题

  •  数据库排序规则选utf8_general_ci(还是建议通过sql语句创建数据库)

  • user表,在真实开发中,还需要有以下几个字段: 
  • version:乐观锁、deleted:逻辑删除、gmt_create:创建时间、gmt_modified:修改时间

mysql5和mysql8在配置上的区别:

1、驱动不同 2、mysql8需要增加时区配置

#mysql5的配置
spring.datasource.username=root
spring.datasource.password=4.233928
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mysql8的配置
spring.datasource.username=root
spring.datasource.password=4.233928
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

总结:

只需要POJO的User类、一个继承了BaseMapper<T>的UserMapper接口,就可以对User表进行CRUD操作(CRUD方法在BaseMapper<T>接口中定义的)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
public interface UserMapper extends BaseMapper<User>{
    //所有CRUD已经自动完成
}
  • 注意点:我们需要在主启动类上去扫描我们的mapper包下的所有接口 
@SpringBootTest
class MybatisPlusApplicationTests {

	@Autowired(required = false)
	private UserMapper userMapper;
	//userMapper的所有方法来自父类接口BaseMapper,

	@Test
	void contextLoads() {
		System.out.println(userMapper.selectById(1));
	}

}

2、SQL日志的配置

和数据库连接配置一样,都是在application.properties中配置

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

我们所有的sqld现在都是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!

配置日志可以让我们看到sql执行的具体过程 

 3、主键(PRIMARY KEY)生成策略

主键生成策略的几种方式************

	@Autowired(required = false)
	private UserMapper userMapper;
	//userMapper的所有方法来自父类接口BaseMapper

	@Test
	void insertTest(){
		User user = new User();
		user.setName("han");
		user.setAge(23);
		user.setEmail("3928@qq.com");

		int result = userMapper.insert(user);
		System.out.println(result);//受影响的行数
		System.out.println(user);

	}

  •  并没有设置user的id,但是mybatis-plus帮我们自动设置了id

如何指定使用什么主键生成策略?

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @TableId(type = IdType.AUTO)//使用数据库自增主键
    private Long id;

    private String name;
    private Integer age;
    private String email;
}
  • @TableId: 使用什么类型主键的注解
  • 这里使用“AUTO”类型的主键,也就是数据库自增主键,但是前提是我们一定要去数据库中把id字段的“自增”也勾选上

分析@TableId注解源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableId {
    String value() default "";

    IdType type() default IdType.NONE;
}

 打开IdType类:(是一个枚举类)可以看到支持6种主键生成策略

public enum IdType {
    AUTO(0),
    NONE(1),
    INPUT(2),
    ID_WORKER(3),
    UUID(4),
    ID_WORKER_STR(5);

    private int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}

 mybatis-plus官方文档中的说明:


主键生成策略有很多,这里只介绍雪花算法

雪花算法:

  • snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯一!
     

4、update操作

	@Autowired(required = false)
	private UserMapper userMapper;
	//userMapper的所有方法来自父类接口BaseMapper

    @Test
	void updateTest(){
		User user = new User();
		user.setId(5L);
		user.setName("关注我的微信公众号");
		user.setAge(18);

		// 通过条件自动拼接动态sql
		// 注意: updateById 但是参数是一个 对象
		int i = userMapper.updateById(user);
		System.out.println(i);

	}
	@Autowired(required = false)
	private UserMapper userMapper;
	//userMapper的所有方法来自父类接口BaseMapper

    @Test
	void updateTest(){
		User user = new User();
		user.setId(5L);
		user.setAge(18);

		// 通过条件自动拼接动态sql
		// 注意: updateById 但是参数是一个 对象
		int i = userMapper.updateById(user);
		System.out.println(i);

	}

  • 从两个不同的update操作的sql日志可以看出, sql都是mybatis-plus自动帮你动态配置的!省去了mybatis拼接动态sql的繁杂操作
  • 什么是动态sql以及其mybatis实现看下面博客

Mybatis实现动态sql

5、自动填充

创建时间gmt_create(或create_time)、修改时间gmt_modified!(或update_time)这些个操作一般都是自动化完成的,我们不希望手动更新!

**阿里巴巴开发手册:**所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需要自动化!

  • insert的时候,自动填充create_time和update_time这两个字段
  • update时,自动填充(或覆盖、更新)update_time字段

方式一:数据库级别(不建议哦)

改变表

  • 直接在数据库中增加create_time和update_time这两个字段

  •  数据类型记着选datetime
  • 默认值要填上:CURRENT_TIMESTAMP
  • 更新时间必须勾选 :更新

方式二:代码级别

  • 一开始仅仅在表中插入这两个字段,别的什么都没动,那如何在代码中实现在 insert和update的时候,自动填充create_time和update_time这两个字段呢?

在实体类对应字段上添加mybatisplus的一个注解@TableField:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @TableId(type = IdType.AUTO)
    private Long id;

    private String name;
    private Integer age;
    private String email;

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

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    //Date类型的实体类属性中,Date必须是Java.util.Date,而不能是Java.sql.Date
}
  • 具体的填充策略可以在源码中找到
  • @TableField可以去看官方文档的解释

@TableField源码分析:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableField {
    String value() default "";

    String el() default "";

    boolean exist() default true;

    String condition() default "";

    String update() default "";

    FieldStrategy strategy() default FieldStrategy.DEFAULT;

    FieldFill fill() default FieldFill.DEFAULT;

    boolean select() default true;
}
  •  一共有value、el、exist、condition、update、strategy、fill、select这几个属性
public enum FieldFill {
    /**
     * 默认不处理
     */
    DEFAULT,
    /**
     * 插入填充字段
     */
    INSERT,
    /**
     * 更新填充字段
     */
    UPDATE,
    /**
     * 插入和更新填充字段
     */
    INSERT_UPDATE
}
  •  fill属性有DEFAULT, INSERT,UPDATE, INSERT_UPDATE这几种值

 编写处理器来处理这个注解(也就是要我们写具体的填充策略)

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler{
    //插入时的自动填充策略
    //插入时createTime updateTime都要填充
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");//配置日志
        this.setFieldValByName("createTime",new Date(),metaObject);//很明显这是反射
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //更新时的自动填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");//配置日志
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}
  • 这一部分要看官方文档***

测试: 

	@Test
	void insertTest(){
		User user = new User();
		user.setName("tomas");
		user.setAge(23);
		user.setEmail("3928@qq.com");

		int result = userMapper.insert(user);
		System.out.println(result);//受影响的行数
		System.out.println(user);

	}

6、乐观锁

当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁实现方式:

  • 取出记录前,先获取当前version
  • 更新时,version+1
  • 提交更新时,set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败


乐观锁配置

第一步:

  • 先增加version字段,默认为1 (记着同步到实体类)

第二步:配置springboot

在配置类中注册

 另外,有了配置类后,包扫描的注解就可以放在配置类上了,不用放在***Application上了

@MapperScan("com.han.mybatis_plus.mapper")

单线程测试乐观锁: 

	@Test
	void VersionTest(){
		User user = userMapper.selectById(1);
		//修改用户
		user.setAge(100);
		user.setName("乐观锁");
		//更新
		userMapper.updateById(user);
		User updatedUser = userMapper.selectById(1);
	}
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1ee47d9e] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@797526745 wrapping com.mysql.cj.jdbc.ConnectionImpl@5afbd567] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email,create_time,update_time,version FROM user WHERE id=? 
==> Parameters: 1(Integer)
<==    Columns: id, name, age, email, create_time, update_time, version
<==        Row: 1, 乐观锁, 100, test1@qq.com, null, 2021-11-15 15:07:10, 1
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1ee47d9e]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@22d9bc14] was not registered for synchronization because synchronization is not active
2021-11-15 15:07:32.946  INFO 13880 --- [           main] c.h.m.handler.MyMetaObjectHandler        : start update fill ....
JDBC Connection [HikariProxyConnection@1373300625 wrapping com.mysql.cj.jdbc.ConnectionImpl@5afbd567] will not be managed by Spring
==>  Preparing: UPDATE user SET name=?, age=?, email=?, update_time=?, version=? WHERE id=? AND version=? 
==> Parameters: 乐观锁(String), 100(Integer), test1@qq.com(String), 2021-11-15 15:07:32.946(Timestamp), 2(Integer), 1(Long), 1(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@22d9bc14]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@303c55fa] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@166710672 wrapping com.mysql.cj.jdbc.ConnectionImpl@5afbd567] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email,create_time,update_time,version FROM user WHERE id=? 
==> Parameters: 1(Integer)
<==    Columns: id, name, age, email, create_time, update_time, version
<==        Row: 1, 乐观锁, 100, test1@qq.com, null, 2021-11-15 15:07:32, 2
<==      Total: 1

7、查询操作

//测试查询
@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}

//测试批量查询
public void testSelectBatchId(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}

//按条件查询之--使用Map操作
@Test
public void testSelectBatchIds(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("name","阿峧说java");
    map.put("age","18");

    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

8、分页查询

原始sql使用limit进行分页

MybatisPlus内置了分页插件,如何使用?

1、在配置类中配置拦截器

// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

2、直接使用Page对象即可

// 测试分页查询
@Test
public void testPage(){
    // 参数一: 当前页
    // 参数二: 页面大小
    // 使用了分页插件之后,所有的分页操作变得简单了
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page, null);

    page.getRecords().forEach(System.out::println);
    System.out.println(page.getTotal());
}

 9、逻辑删除

管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

物理删除:从数据库中直接移除

逻辑删除: 在数据库中没有被移除,而是通过一个变量来让他失效! deleted=0=>deleted=1

 1.在数据表中增加一个deleted字段

 2.实体类中增加属性

//逻辑删除
@TableLogic
private Integer deleted;

 3.配置

//注册逻辑删除
@Bean
public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
}
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

走的是更新操作,不是删除操作,查询的时候会自动过滤删除的数据

10、性能分析插件 

我们在平时的开发中,会遇到一些慢sql.

MybatisPlus也提供了性能分析插件,如果超过这个时间就停止运行!

1.导入插件

@Bean
    @Profile({"dev","test"}) //设置dev 和 test环境开启
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1);//sql执行最大时间1ms
        performanceInterceptor.setFormat(true);//开启格式化支持
        return performanceInterceptor;
    }

2、application.properties中添加设置开发环境

#设置开发环境
spring.profiles.active=dev

 

11、条件构造器(重点***)

下面这些具体含义去文档查看


 测试:

    @Test
    void contextLoads() {
        // 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age",12);
        userMapper.selectList(wrapper).forEach(System.out::println); // 和我们刚才学习的map对比一下
    }

对应SQL:

SELECT id,name,age,email,create_time,update_time,version FROM user 
WHERE 
name IS NOT NULL 
AND
email IS NOT NULL 
AND 
age >= 12

    @Test
    void test2(){
        // 查询名字狂神说
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","狂神说");
        User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List 或者 Map
        System.out.println(user);
    }
SELECT id,name,age,email,create_time,update_time,version 
FROM user 
WHERE 
name = 狂神说

    @Test
    void test3(){
        // 查询年龄在 20 ~ 30 岁之间的用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age",20,30); // 区间
        Integer count = userMapper.selectCount(wrapper);// 查询结果数
        System.out.println(count);
    }
SELECT COUNT(1) 
FROM user 
WHERE age 
BETWEEN 20 AND 30 

    // 模糊查询
    @Test
    void test4(){
        // 查询年龄在 20 ~ 30 岁之间的用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 左和右  t%
        wrapper
                .notLike("name","e")
                .likeRight("email","t");

        List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
        maps.forEach(System.out::println);
    }
 SELECT id,name,age,email,create_time,update_time,version 
FROM user 
WHERE 
name NOT LIKE e AND email LIKE t 

    // 模糊查询
    @Test
    void test5(){

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // id 在子查询中查出来
        wrapper.inSql("id","select id from user where id<3");

        List<Object> objects = userMapper.selectObjs(wrapper);
        objects.forEach(System.out::println);
    }
SELECT id,name,age,email,create_time,update_time,version FROM user 
WHERE id IN (select id from user where id<3) 

    //测试六
    @Test
    void test6(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 通过id进行排序
        wrapper.orderByAsc("id");

        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }
SELECT id,name,age,email,create_time,update_time,version FROM user ORDER BY id ASC 

12、代码生成器

官方文档的配置:

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    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.isNotBlank(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");//projectPath为当前项目目录
        gc.setOutputDir(projectPath + "/src/main/java");//指定生成的代码输出到哪个目录下
        gc.setAuthor("韩T");//设置作者
        gc.setOpen(false);
        gc.setFileOverride(false);//是否覆盖之前自动生成的
        gc.setServiceName("%sService");//去掉iService的i前缀
        gc.setIdType(IdType.ID.WORKER);//设置主键自增策略
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("密码");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));//模块名
        pc.setParent("com.baomidou.ant");//上面这个模块的父模块
        pc.setEntity("entity");//设置实体类的包名
        pc.setMapper("mapper");//设置mapper层的包名
        pc.setService("service");//设置service层的包名
        pc.setController("controller");//设置controller层的包名       
        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 projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        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.setNaming(NamingStrategy.underline_to_camel);//命名规则:下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库到实体类的命名规则:下划线转驼峰命名
        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);//设置lombok
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));//控制台输入要映射的表名字(可以是多张表)
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        strategy.setLogicDeleteFieldName("deleted");//自动设置“deleted”这个字段作为逻辑删除字段
        //自动填充策略
        TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate); tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);

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


        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

也可以这么配置(狂神的配置):

import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; 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 java.util.ArrayList; 

// 代码自动生成器 
public class KuangCode {
public static void main(String[] args) {
    // 需要构建一个 代码自动生成器 对象 
    AutoGenerator mpg = new AutoGenerator(); 
    
    // 配置策略 
    // 1、全局配置 
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir"); 
    gc.setOutputDir(projectPath+"/src/main/java");
    gc.setAuthor("狂神说"); gc.setOpen(false);
    gc.setFileOverride(false);
    
    // 是否覆盖
    gc.setServiceName("%sService");
    
    // 去Service的I前缀
    gc.setIdType(IdType.ID_WORKER);
    gc.setDateType(DateType.ONLY_DATE);
    gc.setSwagger2(true);
    mpg.setGlobalConfig(gc);
    
    //2、设置数据源
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("123456");
    dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);
    
    //3、包的配置
    PackageConfig pc = new PackageConfig();
    //只需要改实体类名字 和包名 还有 数据库配置即可
    pc.setModuleName("blog"); pc.setParent("com.kuang");
    pc.setEntity("entity"); pc.setMapper("mapper");
    pc.setService("service"); pc.setController("controller");
    mpg.setPackageInfo(pc);
    
    //4、策略配置
    StrategyConfig strategy = new StrategyConfig();
  strategy.setInclude("blog_tags","course","links","sys_settings","user_record"," user_say");
    
    // 设置要映射的表名
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    strategy.setEntityLombokModel(true);
    
    // 自动lombok;
    strategy.setLogicDeleteFieldName("deleted"); 
    
    // 自动填充配置
    TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
    TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();
    tableFills.add(gmtCreate); tableFills.add(gmtModified);
    strategy.setTableFillList(tableFills);
    
    // 乐观锁
    strategy.setVersionFieldName("version");
    strategy.setRestControllerStyle(true);
    strategy.setControllerMappingHyphenStyle(true);
    
    // localhost:8080/hello_id_2 
    mpg.setStrategy(strategy);
    mpg.execute(); //执行 
	}
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值