springboot配置MyBatisPlus +代码生成整合

1.完成生成代码后的效果图

代码生成后的项目结构图.png

2.贴出来pom文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
         
    
    com.wsy
    mybatis_plus_demo
    0.0.1-SNAPSHOT
    war
    mybatis_plus_demo
    Demo project for Spring Boot

    
        1.8
        2.2.0
        1.5.9.RELEASE
        2.0
        2.6.1
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            io.springfox
            springfox-swagger2
            ${swagger2.version}
        
        
            io.springfox
            springfox-swagger-ui
            ${swagger2.version}
        
        
        
            org.springframework.boot
            spring-boot-devtools
            true
        
        
        
        
            com.baomidou
            mybatis-plus
            ${mybatisplus.version}
        
        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            1.0.4
        
        
        
            org.apache.velocity
            velocity-engine-core
            ${velocity.version}
        
        
        
            mysql
            mysql-connector-java
            5.1.26
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
            ${springboot.version}
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.6
        
        
        
            org.projectlombok
            lombok
            1.16.18
        
        
        
            ch.qos.logback
            logback-classic
        

    

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



3.application-del.yml

server:
  port: 8080
  # 配置项目根路径
  context-path: /demo
spring:
  datasource:
    # 使用阿里的Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    # 填写你数据库的url、登录名、密码和数据库名
    url: jdbc:mysql://localhost:3306/eth?useSSL=false&characterEncoding=utf8
    username: root
    password: root123456
    druid:
      # 连接池的配置信息
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      # 配置DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # 配置DruidStatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP白名单(没有配置或者为空,则允许所有访问)
        allow: 127.0.0.1,192.168.163.1
        # IP黑名单 (存在共同时,deny优先于allow)
        deny: 192.168.1.73
        #  禁用HTML页面上的“Reset All”功能
        reset-enable: false
        # 登录名
        login-username: admin
        # 登录密码
        login-password: 123456
#devtools热部署
  devtools:
    restart:
      enabled: true
      #设置重启的目录
      additional-paths: src/main/java
      #classpath目录下的WEB-INF文件夹内容修改不重启
      additional-exclude: WEB-INF/**

#mybatisPlus
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  type-aliases-package: com.wsy.mybatis_plus_demo.entity
  configuration:
    map-underscore-to-camel-case: true
    # 打印sql日志信息
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level: com.wsy.mybatis_plus_demo.mapper.debug

4.DataSourceConfig.java

package com.wsy.mybatis_plus_demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

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

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

}

5.MyBatisPlusConfig

package com.wsy.mybatis_plus_demo.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//配置mapper扫描路径
@MapperScan("com.wsy.mybatis_plus_demo.mapper")
@Configuration
public class MyBatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor page =new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }
}

6.项目中的sql信息

表信息.png

7.配置\src\test\java\com\wsy\mybatis_plus_demo\MpGenerator.java

package com.wsy.mybatis_plus_demo;

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

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

/**
 * 

* 代码生成器演示 *

*/ public class MpGenerator { final static String resourcesPath = "E:\\git_repo\\mybatis_plus_demo\\src\\main\\resources"; /** *

* MySQL 生成演示 *

*/ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 选择 freemarker 引擎,默认 Veloctiy //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("E:\\git_repo\\mybatis_plus_demo\\src\\main\\java"); gc.setAuthor("shine"); gc.setFileOverride(true); //是否覆盖 gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setMapperName("%sDao"); gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root123456"); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/eth?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix(new String[] { "tb_" });// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 strategy.setInclude(new String[] { "tb_user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定义 service 父类 // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定义 service 实现类父类 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.wsy.mybatis_plus_demo"); //配置模块名 // pc.setModuleName() pc.setController("controller"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.impl"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map map = new HashMap(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定义 xxList.jsp 生成 List focList = new ArrayList(); /* focList.add(new FileOutConfig("/template/list.jsp.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return "D://my_" + tableInfo.getEntityName() + ".jsp"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);*/ // 调整 xml 生成目录演示 focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return resourcesPath +"/mapper/" +tableInfo.getEntityName() + "Mapper.xml"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 关闭默认 xml 生成,调整生成 至 根目录 TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc); // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 // mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println(mpg.getCfg().getMap().get("abc")); } }

运行MpGenerator.java后:
entity-->User.java

package com.wsy.mybatis_plus_demo.entity;

import com.baomidou.mybatisplus.enums.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;

/**
 * 

* *

* * @author shine * @since 2019-07-20 */ @TableName("tb_user") public class User extends Model { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; private String name; private Integer age; private String email; @TableField("manager_id") private Integer managerId; @TableField("create_time") private Date createTime; public Integer getId() { return id; } public User setId(Integer id) { this.id = id; return this; } public String getName() { return name; } public User setName(String name) { this.name = name; return this; } public Integer getAge() { return age; } public User setAge(Integer age) { this.age = age; return this; } public String getEmail() { return email; } public User setEmail(String email) { this.email = email; return this; } public Integer getManagerId() { return managerId; } public User setManagerId(Integer managerId) { this.managerId = managerId; return this; } public Date getCreateTime() { return createTime; } public User setCreateTime(Date createTime) { this.createTime = createTime; return this; } @Override protected Serializable pkVal() { return this.id; } @Override public String toString() { return "User{" + ", id=" + id + ", name=" + name + ", age=" + age + ", email=" + email + ", managerId=" + managerId + ", createTime=" + createTime + "}"; } }

mapper-->UserDao.java

package com.wsy.mybatis_plus_demo.mapper;

import com.wsy.mybatis_plus_demo.entity.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;

/**
 * 

* Mapper 接口 *

* * @author shine * @since 2019-07-20 */ public interface UserDao extends BaseMapper { }

resource/mapper--->UserMapper.xml





    
    
        
        
        
        
        
        
    

    
    
        id, name, age, email, manager_id AS managerId, create_time AS createTime
    



service-->UserServiceImpl.java

package com.wsy.mybatis_plus_demo.service.impl;

import com.wsy.mybatis_plus_demo.entity.User;
import com.wsy.mybatis_plus_demo.mapper.UserDao;
import com.wsy.mybatis_plus_demo.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 

* 服务实现类 *

* * @author shine * @since 2019-07-20 */ @Service public class UserServiceImpl extends ServiceImpl implements UserService { }

controller-->UserController.java

package com.wsy.mybatis_plus_demo.controller;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

/**
 * 

* 前端控制器 *

* * @author shine * @since 2019-07-20 */ @Controller @RequestMapping("/user") public class UserController { }

mybatisPlus官网:https://mp.baomidou.com/

你可能感兴趣的:(springboot配置MyBatisPlus +代码生成整合)