已有的springcloud+mybatis项目升级为mybatis-plus代码方法

作者:袖梨 2021-03-11

本篇文章小编给大家分享一下已有的springcloud+mybatis项目升级为mybatis-plus代码方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

已有的springcloud+mybatis项目升级为mybatis-plus

项目模块目录

将mybatis依赖替换为mybatis-plus

修改配置文件

实体类如果与数据库不同名需要加上@TableName

@Data
@TableName("project_base")
public class ProjectBase {
 @TableId(value = "id", type = IdType.UUID)//id看具体项目要求如果是后台生成则不需要type属性,如果不是后台生成不管是自增还是唯一键还是填入都需type属性
  private String id;
	 private String prjid;

  private String ccode;

  private String cname;

  private String orgbuild;

  @TableField(fill = FieldFill.INSERT_UPDATE)、//自动填充时间需要一个继承MetaObjectHandler的类,下一个
  private Date createtime;
  @TableField(fill = FieldFill.UPDATE)
  private Date updatetime;
  @TableLogic//需要配置文件开启逻辑删除
  private Boolean del;

  @Version//版本字段数据库不是一定为version只需要在版本字段上加上注解就可以
  private Integer version;
package com.itpm.server.Handler;

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

import java.util.Date;

@Component
@Slf4j
public class MyMateHandler 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("updatatime",new Date(),metaObject);
  }
}

继承BaseMapper

原有接口可以不变,也可以把同名的接口名改了,比如plus的insert和原有的insert同名

package com.itpm.server.mapper.project;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itpm.server.domain.project.ProjectBase;
import com.itpm.server.domain.project.ProjectBaseExample;
import com.itpm.server.dto.project.ProjectBaseDto;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface ProjectBaseMapper extends BaseMapper {
  long countByExample(ProjectBaseExample example);

  int deleteByExample(ProjectBaseExample example);


  int deleteByPrimaryKey(String id);

  int insertlist(List list);

  int insert(ProjectBase record);

  int insertSelective(ProjectBase record);

  List selectByExample(ProjectBaseExample example);

  ProjectBaseDto selectByPrimaryKey(String id);

  int updateByExampleSelective(@Param("record") ProjectBase record, @Param("example") ProjectBaseExample example);

  int updateByExample(@Param("record") ProjectBase record, @Param("example") ProjectBaseExample example);

  int updateByPrimaryKeySelective(ProjectBase record);

  int updateByPrimaryKey(ProjectBase record);

  ProjectBaseDto selectByPrjid(Map map);

  List selectByprojectoverview(String prjid);

  List selectProjectByExample(ProjectBaseExample example);

  List selectProjectByparams(@Param("record") Map record);

}

Service层

service层可以继承IService。如果想都自己写不继承也可以

代码生成器

与之前的mybatis代码生成器不冲突,可以选择也可以一起用

我的要生成在公共模块server下

 
        com.baomidou
        mybatis-plus-generator
        3.0.6
      
 
        org.freemarker
        freemarker
        2.3.29
      

```默认的是freemaker模板可以用其他的,需要导入其他依赖并且代码设置如下,当然可以做成一个util方便,mapper.xml默认生成在mapper层下xml包下,如果需要在resouce下生成需要自定义输出位置

package com.itpm.generator.server;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
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.io.File;
import java.util.ArrayList;
import java.util.List;

public class ProjectKing {
  public static void main(String[] args) {
    //需要构建一个代码自动生成器对象
    AutoGenerator autoGenerator = new AutoGenerator();
    //配置策略
    //1.全局配置
    GlobalConfig globalConfig = new GlobalConfig();
    File file = new File("server");
    String path = file.getAbsolutePath();
//    String property = System.getProperty("user.dir");
    globalConfig.setOutputDir(path + "/src/main/java");
    globalConfig.setAuthor("蒋磊");
    globalConfig.setOpen(false);
    globalConfig.setBaseResultMap(true);
    globalConfig.setBaseColumnList(true);
    globalConfig.setFileOverride(false);//是否覆盖
    globalConfig.setServiceName("%sService");//去service的i前缀
    globalConfig.setIdType(IdType.UUID);
    globalConfig.setDateType(DateType.ONLY_DATE);
    globalConfig.setSwagger2(true);
    autoGenerator.setGlobalConfig(globalConfig);
    //2设置数据源
    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setUrl("jdbc:mysql://itpm.itycu.com/itpm?characterEncoding=UTF8&autoReconnect=true&&allowMultiQueries=true");
    dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
    dataSourceConfig.setUsername("root");
    dataSourceConfig.setPassword("Itycu.8594");
    dataSourceConfig.setDbType(DbType.MYSQL);
    autoGenerator.setDataSource(dataSourceConfig);
    //包的配置
    PackageConfig packageConfig = new PackageConfig();
    packageConfig.setModuleName("server");
    String a="project";
    packageConfig.setParent("com.itpm");
//    packageConfig.setEntity("entity");
//    packageConfig.setMapper("mapper");
//    packageConfig.setService("service");
//    packageConfig.setController("controller");
    packageConfig.setEntity("domain."+a);
    packageConfig.setMapper("mapper."+a);
    packageConfig.setService("service."+a);
    packageConfig.setServiceImpl("service."+a+".impl");
    packageConfig.setController("controller."+a);
   // 自定义配置
    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 focList = new ArrayList<>();
    // 自定义配置会被优先输出
    focList.add(new FileOutConfig(templatePath) {
      @Override
      public String outputFile(TableInfo tableInfo) {
        // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
        return path + "/src/main/resources/mapper/" + a
            + "/" + 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);
    autoGenerator.setCfg(cfg);
    templateConfig.setXml(null);
    autoGenerator.setTemplate(templateConfig);

    autoGenerator.setPackageInfo(packageConfig);
    //4策略配置
    StrategyConfig strategyConfig = new StrategyConfig();
    strategyConfig.setNaming(NamingStrategy.underline_to_camel);
    strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
    ArrayList objects = new ArrayList<>();
//    objects.add("etest");
    objects.add("rtest");
    strategyConfig.setInclude(objects.toArray(new String[objects.size()]));//设置要映射的表名

//    strategyConfig.setSuperEntityClass("");
    strategyConfig.setEntityLombokModel(true);//自动lombok
    strategyConfig.setRestControllerStyle(true);
    strategyConfig.setLogicDeleteFieldName("deletedd");//逻辑删除字段
    //自动填充配置
    TableFill createtime = new TableFill("create_time", FieldFill.INSERT);
    TableFill updatetime = new TableFill("update_time", FieldFill.UPDATE);
    ArrayList tableFills = new ArrayList<>();
    strategyConfig.setTableFillList(tableFills);
    //乐观锁
    strategyConfig.setVersionFieldName("berv");
    strategyConfig.setRestControllerStyle(true);
    strategyConfig.setControllerMappingHyphenStyle(true);//localhost:8080/hello_id_2
    autoGenerator.setStrategy(strategyConfig);
    autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
    //执行
    autoGenerator.execute();
 }
}

相关文章

精彩推荐