zoukankan      html  css  js  c++  java
  • mybatisPlus生成项目

    记录是为了更好的成长!

    mybatisPlus生成工具,这里以spgingBoot构建项目说明

    1、引入jar

    如果使用 https://start.spring.io/ 构建springBoot项目只需选 web 和 mysql即可,然后加入下面的依赖到pom文件中

         <!-- 阿里巴巴druid数据库连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.10</version>
            </dependency>
            
            <!-- mybatisplus与springboot整合 -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>2.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>2.1</version>
            </dependency>

    2、引入一个工具类

    package com.share.common.utils;
    
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.ClassUtils;
    
    /**
     * @Description:通用工具类
     */
    
    public class PropertiesUtil {
    
        private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
    
        /**
         * @Description: 获取根路径下的properties文件
         * @param fileName
         * @return
         * @throws FileNotFoundException Properties
         */
        public static Properties getProperties(String fileName) throws FileNotFoundException {
    
            String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
            String filePath = rootPath + fileName;
    
            log.info("加载的properties属性文件是:" + filePath);
    
            Properties properties = new Properties();
    
            // 读取属性文件a.properties
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            try {
                properties.load(in);
            } catch (IOException e) {
                log.info("读取文件失败");
            }
            return properties;
        }
    }

     3、生成代码的java文件

    public class MybatisplusGenerator {
        
        public static void main(String[] args) throws FileNotFoundException {
    
            //读取配置文件
            String fileName = "application-dev.properties";
            Properties properties = PropertiesUtil.getProperties(fileName);
            
            //获取DB连接信息
            String drivername = (String) properties.get("spring.datasource.driverClassName");
            String url = properties.getProperty("spring.datasource.url");
            String username = properties.getProperty("spring.datasource.username");
            String password = properties.getProperty("spring.datasource.password");
            
            AutoGenerator mpg = new AutoGenerator();
    
            /*
             * 配置路径
             */
            String projectPath = System.getProperty("user.dir"); // 获取项目路径
            String objPath = projectPath + "/src/main/java"; // 获取java目录
            String parentPackage = "com.share.modules.biz"; // 配置包路径
    
            /*
             * 全局配置
             */
            GlobalConfig gc = new GlobalConfig();
            gc.setOutputDir(objPath); // 配置路径
            gc.setOpen(false); // 是否打开生成的文件夹
            gc.setAuthor("author"); // author
            /* 自定义文件命名,注意 %s 会自动填充表实体属性! */
            gc.setMapperName("%sMapper"); // 设置mapper接口后缀
            gc.setServiceName("%sService"); // 设置Service接口后缀
            gc.setServiceImplName("%sServiceImpl"); // 设置Service实现类后缀
            gc.setControllerName("%sController"); // 设置controller类后缀
            gc.setXmlName("%sMapper"); // 设置sql映射文件后缀
            gc.setFileOverride(false); // 是否覆盖同名文件,默认是false
            gc.setActiveRecord(false); // 不需要ActiveRecord特性的请改为false
            gc.setEnableCache(false); // XML 二级缓存
            gc.setBaseResultMap(true); // XML ResultMap
            gc.setBaseColumnList(false); // XML columList
            mpg.setGlobalConfig(gc);
    
            /*
             * 数据源配置
             */
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setDbType(DbType.MYSQL).setDriverName(drivername).setUrl(url).setUsername(username).setPassword(password);
            mpg.setDataSource(dsc);
    
            /*
             * 策略配置
             */
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel) // 表名生成策略
                    .setRestControllerStyle(true); // 设置controller自动加RestController注解
            //.setInclude(new String[] {"rs_user"}); //修改替换成你需要的表名,多个表名传数组,如果注释掉就生成库中所有的表
            // .setTablePrefix(new String[] { "t_" }) // 此处可以修改为您的表前缀
            ;
            mpg.setStrategy(strategy);
    
            // 包配置
            PackageConfig packageConfig = new PackageConfig();
            packageConfig.setParent(parentPackage).setController("controller")
            /*
             * .setService("service") //服务接口 .setServiceImpl("service.impl") //服务实现
             * .setMapper("mapper") //dao层 .setXml("mapper") //dao层对应的xml文件
             * .setEntity("entity")
             */; // pojo对象
            mpg.setPackageInfo(packageConfig);
    
            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };
            
    
            // 自定义xml的存放路径
            List<FileOutConfig> focList = new ArrayList<>();
            focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义Mapper.xml文件存放的路径
                    return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "-mapper.xml";
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
            
            // 配置生成的资源模板
            TemplateConfig templateConfig = new TemplateConfig();
            templateConfig.setController(null);    //不生成controller
            templateConfig.setService(null);    //不生成service
            templateConfig.setServiceImpl(null);//不生成service实现
            templateConfig.setXml(null);        // 关闭默认 xml 生成,调整生成 至 根目录
            
            mpg.setTemplate(templateConfig);
    
            // 执行生成
            mpg.execute();
        }
    }

    4、运行java文件,刷新项目即可 

    5、启动springBoot项目需要在启动类加@MapperScan注解,并指定mapper的目录,否则会报错ibatis绑定异常

    6、生成的项目并不一定满足我们的需要,需要自定义sql查询,直接在生成的mapper接口和mapper映射文件中追加即可

    7、 我习惯生成entity和mapper, 自己写service接口和实现类

    注意:
         如果需要自定义sql语句,就必须要在配置文件中指定   mybatis-plus.mapper-locations=classpath:mappers/*.xml
                            不能写成   mybatis.mapper-locaitons=classpath:mappers/*.xml

     github示例: https://github.com/kh5218/DemoForSpringBoot/tree/master/mybatisplus

    以上内容代表个人观点,仅供参考,不喜勿喷。。。

  • 相关阅读:
    JDK9对集合添加的优化
    IO异常的处理
    动态创建分页 LINQ+EF
    TypeError at /admin/booktest/book_infor/add/ __str__ returned non-string (type bytes)
    TypeError at /admin/booktest/bookinfo/ expected string or buffer
    linux下的 pycharm 2016.3d的注册码
    解决ubantu下的pycharm输入中文的问题
    .pip的时候出现Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None))…………
    Day06
    Day05
  • 原文地址:https://www.cnblogs.com/newbest/p/10853144.html
Copyright © 2011-2022 走看看