spring boot+mybatis plus自动生成代码

spring boot 版本2.1.13.RELEASE,mybatis plus 版本3.1.0,数据库mysql,连接池druid

直接上pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.13.RELEASE
         
    
    com.example.jany
    mybatis-plus-demo
    0.0.1-SNAPSHOT
    mybatis-plus-demo
    Demo project for Spring Boot

    
        UTF-8
        UTF-8
        1.8
        1.1.9
        2.7.0
        3.1.0
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatisplus.version}
        

        
            com.baomidou
            mybatis-plus
            ${mybatisplus.version}
        

        
        
            com.alibaba
            druid-spring-boot-starter
            ${druid.version}
        

        
            io.springfox
            springfox-swagger2
            ${swagger.version}
        
        
            io.springfox
            springfox-swagger-ui
            ${swagger.version}
        

        
        
            com.baomidou
            mybatis-plus-generator
            ${mybatisplus.version}
        
        
        
            org.apache.velocity
            velocity
            1.7
        
        
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            

            
        
    




application.yml配置

 

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis-plus:
  mapper-locations: mapper/*.xml
  type-aliases-package: com.example.jany.demo.model
  global-config:
     id-type: 0
     field-strategy: 2
     capital-mode: true
     refresh-mapper: true
package com.example.jany.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        //reg.addInitParameter("allow", "127.0.0.1"); //白名单
        reg.addInitParameter("resetEnable", "false");
        return reg;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map initParams = new HashMap();
        //设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
        filterRegistrationBean.addInitParameter("principalSessionName", "");
        filterRegistrationBean.addInitParameter("aopPatterns", "com.example.demo.service");
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    // 配置事物管理器
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

MybatisPlusConfig.java
package com.example.jany.demo.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {



    /***
     * plus 的性能优化
     * @return
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();
        /**/
        performanceInterceptor.setMaxTime(1000);
        /**/
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     *  mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType(DbType.MYSQL.getDb());
        return page;
    }


}

package com.example.jany;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.jany.*.mapper")
@SpringBootApplication
public class MybatisPlusDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusDemoApplication.class, args);
    }

}

 

代码生成CodeGenerator.Java

 

package com.example.jany.demo;

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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jany
 * @ClassName: CodeGeneration
 * @Description: 代码生成器
 * @date 2018年1月25日 下午2:55:14
 */
public class CodeGenerator {

    private static String PROJECT_PATH = System.getProperty("user.dir")  + "\\spring-boot-demo\\mybatis-plus-demo\\";

    private static String OUTPUT_DIR = PROJECT_PATH + "\\src\\main\\java";

    //mapper.xml SQL映射文件目录
    private static String OUTPUT_DIR_MAPPER = PROJECT_PATH + "\\src\\main\\resources";

    private static String OUTPUT_BASE_PATH = "\\com\\example\\jany\\demo";

    /**
     * @param args
     * @Title: main
     * @Description: 生成
     */
    public static void main(String[] args) {
        //ResourceBundle rb = ResourceBundle.getBundle("zq_blog"); //TODO 配置文件信息
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(OUTPUT_DIR);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor("jany");// 作者

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[]{"sys_"});// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[]{"sys_user"}); // 需要生成的表

        strategy.setSuperServiceClass(null);
        strategy.setSuperServiceImplClass(null);
        strategy.setSuperMapperClass(null);
        strategy.setSuperControllerClass("com.example.jany.common.controller.BaseController");
        strategy.setEntityLombokModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.jany.demo");
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        pc.setXml("xml");
        mpg.setPackageInfo(pc);

        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map map = new HashMap();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };
        //指定xml生成路径
        List focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "src/main/resources/" + "/mapper/" + 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("/generator/service.java.vm");
        //tc.setServiceImpl("/generator/serviceImpl.java.vm");
        //tc.setEntity("/generator/entity.java.vm");
        //tc.setMapper("/generator/mapper.java.vm");
        //以指定模板生成controller
        tc.setController("/generator/templates/controller.java.vm");
        // 关闭默认 xml 生成,调整生成 至 根目录
        tc.setXml(null);
        //tc.setXml("/generator/mapper.xml.vm");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);


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

    }

}

 如果要自定义模板可参考

 

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.example.jany.common.entity.Query;
import com.example.jany.common.entity.Response;
import com.example.jany.common.entity.PageResponse;
import com.example.jany.common.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller extends BaseController{

    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
     * 保存、修改 【区分id即可】
     * @param ${table.entityPath}  传递的实体
     * @return Response转换结果
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public Response save(@RequestBody ${entity} ${table.entityPath}){
        try {
            if(${table.entityPath}.getId()!=null){
                    ${table.entityPath}Service.updateById(${table.entityPath});
            }else{
                    ${table.entityPath}Service.save(${table.entityPath});
            }
            return success(1);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("保存对象失败!"+e.getMessage());
        }
    }

    //删除对象信息
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public Response delete(@PathVariable("id") Long id){
        try {
            ${table.entityPath}Service.removeById(id);
            return success(id);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("删除对象失败!"+e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Response<${entity}> get(@PathVariable("id")Long id) {
        return success(${table.entityPath}Service.getById(id));
    }


    //查看所有的员工信息
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Response> list(){
        return success(${table.entityPath}Service.list());
    }


    /**
    * 分页查询数据:
    * @param query 查询对象
    * @return PageList 分页对象
    * ${entity}Query
    */
    @RequestMapping(value = "/json",method = RequestMethod.POST)
    public PageResponse<${entity}> json(@RequestBody Query query) {
        Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getPageSize());
        return successPage(${table.entityPath}Service.page(page));
    }
}

 

 

你可能感兴趣的:(spring,boot)