不熟悉配置文件 就多生成几次 自然就会了 注意配置里面的输出路径,默认包名!

         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatisplus所需要的jar包-->
          <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>mybatis-plus-core</artifactId>
                    <groupId>com.baomidou</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-core</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>mybatis-plus-extension</artifactId>
                    <groupId>com.baomidou</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
         <!-- sfl4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>

生成工具类 需要调整表名、生成目录、配置文件名字

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.Serializable;
import java.util.*;

public class MybaitsUtils {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-hss"); //不要加后缀
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setEntityName("%sEntity");// 设置实体类后缀
        gc.setMapperName("%sDao"); //mapper后缀
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        gc.setActiveRecord(false);
        gc.setAuthor(rb.getString("author"));
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(rb.getString("jdbc.driver"));
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[]{"hss_history"}); // 需要生成的表,可多个表
        strategy.setEntityLombokModel(true); // 是否 lombok
        strategy.setRestControllerStyle(true);
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("entity");
        pc.setMapper("dao");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        // 调整 domain 生成目录演示
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/work/chenshuang/test/entity/" + tableInfo.getEntityName()+".java";
            }
        });

        // 调整 xml 生成目录演示 需要生成再解开
/*        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml") + tableInfo.getEntityName() + "Mapper.xml";
            }
        });*/
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController("/templates/controller.java.vm");
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }

}

配置类 mybatiesplus-molo.properties

#src路径
OutputDir=D:\\Molo\\molo_web_service\\src\\main\\java\\
#mapper.xml 输出路径
OutputDirXml=D:\\Molo\\molo_web_service\\src\\main\\resources\\mapper\\sys\\
#domain、query路径
OutputDirBase=D:\\Molo\\molo_web_service\\src\\main\\java\\
#作者
author=koukoulaoshi
#默认包名
parent=com.molomessage.message.module

#数据库配置信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.60.4:3306/cloud_data2021?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
jdbc.user=root
jdbc.pwd=123456

模板文件 放置自己项目的 src/main/resources/templates 目录下 文件名和工具类里面对应
controller.java.vm

package ${package.Controller};

import com.alibaba.fastjson.JSONArray;
import com.molomessage.message.*.entity.${entity};
import com.molomessage.message.*.query.${entity}Query;
import com.molomessage.message.*.service.I${entity}Service;
import com.molomessage.message.sys.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author chen
 * @version 2.0
 * @date ${date}
 * ${entity}接口
 */
@RestController
@RequestMapping("/${table.entityPath}")
public class ${table.controllerName} {
    @Autowired
    private ${table.serviceName} ${table.entityPath}Service;

    /**
     * 保存
     *
     * @param ${table.entityPath} 传递的实体
     * @return R转换结果
     */
    //@TokenVerification
    //@NoteLogAnnotation("添加${entity}数据")
    @PostMapping("/add")
    public R add(${entity} ${table.entityPath}) {

        return ${table.entityPath}Service.insertOne(${table.entityPath});
    }

    /**
     * 修改
     *
     * @param ${table.entityPath} 传递的实体
     * @return R转换结果
     */
    //@TokenVerification
    //@NoteLogAnnotation("修改${entity}数据")
    @PostMapping("/update")
    public R update(${entity} ${table.entityPath}) {
        return ${table.entityPath}Service.update${entity}(${table.entityPath});
    }

    /**
     * 删除   逻辑删除 修改状态is_delete 为0
     *
     * @param ${table.entityPath} 传递的实体
     * @return R转换结果
     */
    //@TokenVerification
    //@NoteLogAnnotation("删除${entity}数据")
    @PostMapping("/delete")
    public R delete(@RequestParam String id) {
        //转json数组
        JSONArray jsonArray = null;
        try {
            jsonArray = JSONArray.parseArray(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("参数格式错误,正确方式['?','?','?']");
        }
        List<String> ids = jsonArray.toJavaList(String.class);
        return ${table.entityPath}Service.detele${entity}(id);
    }

    /**
     * 批量修改状态
     *
     * @param
     * @return
     */
    @PostMapping("/upState")
    public R upState(@RequestParam String id) {
        //转json数组
        JSONArray jsonArray = null;
        try {
            jsonArray = JSONArray.parseArray(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("参数格式错误,正确格式[?,?,?]");
        }
        List<Long> ids = jsonArray.toJavaList(Long.class);
        return ${table.entityPath}Service.upState(ids);
    }

    /**
     * 查询全部对象信息
     *
     * @param
     * @return
     */
    //@TokenVerification
    //@NoteLogAnnotation("查询全部${entity}数据")
    @GetMapping("/get")
    public R getAll(${entity}Query ${table.entityPath}Query) {
        //带分页和关键字查询并返回
        return ${table.entityPath}Service.selectAll(${table.entityPath}Query);
    }
    
    /**
   * 查询详情
   *
   * @param
   * @return
   */
    //@TokenVerification
    //@NoteLogAnnotation("查询${entity}详情数据")
    @GetMapping("/getDetail")
    public R getDetail(@RequestParam String id) {
        //带分页和关键字查询并返回
        return ${table.entityPath}Service.getDetail(id);
    }

}



    /**
     * 批量修改状态
     *
     * @param
     * @return
     */
    @PostMapping("/upState")
    public R upState(@RequestParam String id) {
        //转json数组
        JSONArray jsonArray = null;
        try {
            jsonArray = JSONArray.parseArray(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("参数格式错误,正确格式[?,?,?]");
        }
        List<Long> ids = jsonArray.toJavaList(Long.class);
        return ${table.entityPath}Service.upState(ids);
    }

    /**
     * 查询全部对象信息
     *
     * @param
     * @return
     */
    //@TokenVerification
    //@NoteLogAnnotation("查询全部${entity}数据")
    @GetMapping("/get")
    public R getAll(${entity}Query ${table.entityPath}Query) {
        //带分页和关键字查询并返回
        return ${table.entityPath}Service.selectAll(${table.entityPath}Query);
    }
    
    /**
   * 查询详情
   *
   * @param
   * @return
   */
    //@TokenVerification
    //@NoteLogAnnotation("查询${entity}详情数据")
    @GetMapping("/getDetail")
    public R getDetail(@RequestParam String id) {
        //带分页和关键字查询并返回
        return ${table.entityPath}Service.getDetail(id);
    }

}

service.java.vm

package ${package.Service};

import com.baomidou.mybatisplus.extension.service.IService;
import com.molomessage.message.module.entity.${entity};
import com.molomessage.message.sys.utils.R;
import com.molomessage.message.module.query.${entity}Query;

import java.util.List;


/**
 * <p>
 * ${entity}服务类
 * </p>
 *
 * @author chen
 * @date ${date}
 */
public interface ${table.serviceName} extends IService<${entity}> {

        //添加一条数据
        R insertOne(${entity} ${table.entityPath});

        //修改一条数据
        R update${entity}(${entity} ${table.entityPath});

        //查询全部
        R selectAll(${entity}Query ${table.entityPath}Query);

        //批量删除数据(更改状态为禁用)
        R detele${entity}(List<Long> id);

        //更改状态
        R upState(List<Long> id);

        //通过id获取详情
        R getDetail(Integer id);
}




serviceImpl.java.vm


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.molomessage.message.module.constant.ModuleConstant;
import com.molomessage.message.module.entity.${entity};
import com.molomessage.message.module.mapper.${entity}Mapper;
import com.molomessage.message.module.query.${entity}Query;
import com.molomessage.message.module.service.I${entity}Service;
import com.molomessage.message.module.service.I${entity}Service;
import com.molomessage.message.module.vo.${entity}VO;
import com.molomessage.message.sys.mapper.DataDictionaryMapper;
import com.molomessage.message.sys.utils.PageReturnList;
import com.molomessage.message.sys.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * <p>
 * ${entity}实现类
 * </p>
 *
 * @author chen
 * @date ${date}
 */
@Service
public class ${entity}ServiceImpl extends ServiceImpl<${entity}Mapper, ${entity}> implements ${table.serviceName} {

    //注入数据字典mapper
    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;
    //注入用户mapper 用作查询用户名字
    @Autowired
    private SysUserMapper sysUserMapper;

    //添加数据
    @Override
    public R insertOne(${entity} ${table.entityPath}) {
        if (StringUtils.isBlank(canvasApi.getName())) return R.error("名称不能为空");
        CanvasApi one = baseMapper.selectOneByName(canvasApi.getName());
        if (one != null) return R.error("名称已存在,请更改");
        int i = baseMapper.insert(canvasApi);
        if (i == ModuleConstant.ZEOR) return R.error("添加失败");
        return R.ok("操作成功");
    }

    //修改数据 根据id修改的
    @Override
    public R update${entity}(${entity} ${table.entityPath}) {
        //根据名字查询数据库 判断是否有重名的数据
        if (${table.entityPath}.getId() == null)R.error("ID不能为空");
        ${entity} one = baseMapper.selectOneByName(${table.entityPath}.getName());
        if (one != null && one.getId() != ${table.entityPath}.getId())return R.error("名称已存在,请更改");
        //设置修改时间
        ${table.entityPath}.setUpTime(new Date());
        int i = baseMapper.updateById(${table.entityPath});
        if (i == ModuleConstant.ZEOR) return R.error("修改失败");
        return R.ok("操作成功");
    }

    //删除数据 根据id删除 更改状态  根据需要 看用物理删除还是逻辑删除
    @Override
    public R detele${entity}(List<Long> ids) {
        //物理删除
        if (ids.size() == ModuleConstant.ZEOR) return R.error("id不能为空");
        int i = baseMapper.deleteBatchIds(ids);
        if (i == ModuleConstant.ZEOR) return R.error("数据已删除,请不要重复提交");
        return R.ok("操作成功");
        //逻辑删除
        for (Long id : ids) {
            ${entity} ${table.entityPath} =baseMapper.selectById(id);
            if (${table.entityPath} ==null)return R.error("数据已删除,请不要重复提交");
            //更改状态
            ${table.entityPath}.setIsDelet(ModuleConstant.ZEOR);
            int i = baseMapper.updateById(${table.entityPath});
            if (i == ModuleConstant.ZEOR) return R.error("删除失败");
        }
        return R.ok("操作成功");

        //批量修改状态  看数据量大小,数据量大 在xml里面循环修改
        @Override
        public R upState (List < Long > ids) {
            if (ids.size() == ModuleConstant.ZEOR) return R.error("Id不能为空");
            List<${entity}> list = new ArrayList<>();
            for (Long id : ids) {
                //根据ID查询数据库
                ${entity} ${table.entityPath} =baseMapper.selectById(id);
                if (${table.entityPath} ==null)return R.error("Id对应数据不存在");
                //获取状态
                Integer state = ${table.entityPath}.getState();
                //状态取反
                state = state == ModuleConstant.ONE ?ModuleConstant.ZEOR : ModuleConstant.ONE;
                //设置状态
                ${table.entityPath}.setState(state);
                ${table.entityPath}.setUpTime(new Date());
                list.add(${table.entityPath});
            }
            int i = baseMapper.updateBatchState(list);
            if (i == ModuleConstant.ZEOR) return R.error("修改失败");
            return R.ok("操作成功");

        }

        //查询全部数据
        @Override
        public R selectAll (${entity}Query ${table.entityPath}Query){
            if (${table.entityPath}Query == null) return R.error("参数错误");
            //高级查询封装条件
            QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
            //根据状态和名字查询
            //不传状态 就显示全部信息
            if (${table.entityPath}Query.getState() != null && !"".equals(${table.entityPath}Query.getState().toString().trim())) {
                queryWrapper.eq("state", ${table.entityPath}Query.getState());
            }
            //关键字查询
            if (${table.entityPath}Query.getKeyword() != null && !${table.entityPath}Query.getKeyword().trim().equals("")) {
                queryWrapper.like("name", ${table.entityPath}Query.getKeyword());
            }
            //排序查询  order  排序的字段sidx
            //排序      调用方法获取和数据库一样的排序字段
            String sidx = SidxProcess.getSidx(${table.entityPath}Query.getSidx());
            String order = ${table.entityPath}Query.getOrder().toUpperCase();
            //查询该字段是否存在
            if (!StringUtils.isEmpty(sidx)) {
                int i = baseMapper.queryCloumn(sidx);
                if (i == 0) return R.error("需要排序的字段不存在");
            }
            //执行条件,是否为asc排序,排序字段数组 
            queryWrapper.orderBy(sidx != null && !"".equals(sidx.trim()), "ASC".equals(order) ? true : false, sidx);

            //分页查询
            IPage<${entity}> userPage = new Page<>(${table.entityPath}Query.getPage(), ${table.entityPath}Query.getLimit());//参数一是当前页,参数二是每页个数
            userPage = baseMapper.selectPage(userPage, queryWrapper);
            //获取分页数据
            List<${entity}> list = userPage.getRecords();
            List<${entity}VO> listVo = new ArrayList<>();
            //循环返回的list  添加状态值
            list.forEach(s -> {
                listVo.add(getVo(s));
            });

            //返回数据封装
            PageReturnList<${entity}VO> returnList = new PageReturnList<>();
            returnList.setList(listVo);
            //当前页
            returnList.setCurrPage(userPage.getCurrent());
            //每页显示条数
            returnList.setPageSize(userPage.getSize());
            //总页数
            returnList.setTotalPage(userPage.getPages());
            //总条数
            returnList.setTotalCount(userPage.getTotal());
            //返回结果到前端
            return R.ok("操作成功", returnList);
        }

        //通过id获取详情
        @Override
        public R getDetail (Integer id){
            if (id == null) return R.error("ID不能为空");
            ${entity} ${table.entityPath} =baseMapper.selectById(id);
            if (${table.entityPath} ==null)return R.error("ID对应数据为空");
                ${entity}VO vo = getVo(${table.entityPath});
            return R.ok("操作成功", vo);
        }

        //处理状态值 返回前端
        private ${entity}VO getVo (${entity} ${table.entityPath}) {
                ${entity}VO vo = new ${entity}VO();
            BeanUtils.copyProperties(${table.entityPath}, vo);
            //查询数据字典 获取是否禁用对应值
            vo.setStateName(dataDictionaryMapper.queryData("sfjy", vo.getState().toString()));
            return vo;
        }
    }

mapper.java.vm


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.molomessage.message.datafuc.entity.${entity};
import com.molomessage.message.datafuc.query.${entity}Query;
import com.molomessage.message.sys.utils.R;
import org.apache.ibatis.annotations.Mapper;


/**
 * <p>
 * ${entity}持久层
 * </p>
 *
 * @author chen
 * @date ${date}
 */
@Mapper
public interface ${entity}Mapper extends BaseMapper<${entity}> {

}

可以写好一套代码后复制到模板里面来 以后就不需要重复写简单的代码了,
分页插件

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//Spring boot方式   分页插件
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {

        return new PaginationInterceptor();
    }
}
Logo

更多推荐