SpringBoot+MybatisPlus+Druid_mysql搭建简单的项目自动生成代码
druid
阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
项目地址:https://gitcode.com/gh_mirrors/druid/druid
免费下载资源
·
数据库
CREATE DATABASE test;
USE test;
CREATE TABLE `user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
`create_time` DATETIME DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户';
项目pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.dyp</groupId> <artifactId>dyp-test</artifactId> <version>0.0.1-SNAPSHOT</version> <name>dyp-test</name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.BUILD-SNAPSHOT</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis的orm插件 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <!--数据库连接jdbc依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql链接依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--阿里druid数据库链接依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>0.10.1</version> <scope>provided</scope> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- Add Spring repositories --> <!-- (you don't need this if you are using a .RELEASE version) --> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> </project>
application.yml 相关的配置
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true username: root password: root druid: initial-size: 5 min-idle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 web-stat-filter: enabled: true url-pattern: "/*" exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*" # DruidStatViewServlet stat-view-servlet: url-pattern: "/druid/*" allow: 127.0.0.1,192.168.1.1 deny: 192.168.1.1 reset-enable: false login-username: admin login-password: 123456 mybatis-plus: mapper-locations: classpath:/com/dyp/dyptest/mapper/*/*.xml typeAliasesPackage: com.dyp.dyptest.entity global-config: id-type: 2 field-strategy: 2 db-column-underline: true refresh-mapper: true configuration: map-underscore-to-camel-case: true cache-enabled: false server: port: 8082
com.dyp.dyptest.config相关配置
package com.dyp.dyptest.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 DataSourcesConfig { @Bean(name="dataSource") @ConfigurationProperties(prefix="spring.datasource") public DataSource dataSource(){ return new DruidDataSource(); } // 配置事物管理器 @Bean(name="transactionManager") public DataSourceTransactionManager transactionManager(){ return new DataSourceTransactionManager(dataSource()); } }
package com.dyp.dyptest.config; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; 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; @Configuration public class DruidConfiguration { @Bean public ServletRegistrationBean startViewServlet(){ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); // IP白名单 servletRegistrationBean.addInitParameter("allow","127.0.0.1"); // IP黑名单(共同存在时,deny优先于allow) servletRegistrationBean.addInitParameter("deny","127.0.0.1"); //控制台管理用户 servletRegistrationBean.addInitParameter("loginUsername","admin"); servletRegistrationBean.addInitParameter("loginPassword","123456"); //是否能够重置数据 servletRegistrationBean.addInitParameter("resetEnable","false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean statFilter(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //添加过滤规则 filterRegistrationBean.addUrlPatterns("/*"); //忽略过滤的格式 filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } }
package com.warrior.config; import com.baomidou.mybatisplus.plugins.PerformanceInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import org.springframework.context.annotation.Profile; @Configuration //扫描dao或者是Mapper接口 @MapperScan("com.dyp.dyptest.mapper*") public class MybatisPlusConfig { /** * mybatis-plus 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType("mysql"); return page; } /** * SQL执行效率插件 * 性能分析拦截器,用于输出每条 SQL 语句及其执行时间 */ @Bean @Profile({"dev","pro"})// 设置 dev pro 环境开启 public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } }
代码生成器代码
package com.dyp.dyptest.Generator; 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.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.dyp.dyptest.config.DataSourcesConfig; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 代码生成器演示 * </p> */ public class CodeGenerator { final static String dirPath = "C://"; public static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true"; public static final String USER_NAME = "root"; public static final String PASSWORD = "root"; public static final String DRIVER = "com.mysql.jdbc.Driver"; public static final String AUTHOR = "dyp"; // 输出到哪个目录 public static final String OUTPUT_FILE = "c:\dyp"; //生成类 public static final String PACKAGE = "com.dyp"; public static void generateByTables(boolean serviceNameStartWithI, String... tableNames) { AutoGenerator mpg = new AutoGenerator(); // 选择 freemarker 引擎,默认 Veloctiy //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(dirPath); gc.setAuthor(AUTHOR); 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("MP%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); 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(DRIVER); dsc.setUsername(USER_NAME); dsc.setPassword(PASSWORD); dsc.setUrl(DB_URL); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix(new String[] { "tb_", "tsys_" });// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 //strategy.setInclude(new String[] { "user" }); // 需要生成的表 strategy.setInclude(tableNames); // 需要生成的表 // 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(PACKAGE); pc.setModuleName("dyptest"); pc.setController("controler"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("serviceImpl"); pc.setXml("mapperXml"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("dyp", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定义 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); /* 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 dirPath + 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("dyp")); } /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { boolean serviceNameStartWithI = false; //指定生成的表名 String[] tableNames = new String[]{"user"}; generateByTables(serviceNameStartWithI, tableNames); } }
package com.dyp.dyptest.controler; import com.dyp.dyptest.entity.User; import com.dyp.dyptest.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.List; /** * <p> * 用户 前端控制器 * </p> * * @author dyp * @since 2019-07-09 */ @Controller @RequestMapping("/dyptest/user") public class UserController { @Autowired IUserService iUserService; @RequestMapping("/add") @ResponseBody public String add() { //insert User user = new User(); user.setUsername("dyp"); user.setCreateTime(new Date()); boolean res = iUserService.insert(user); return res ? "success" : "fail"; } @RequestMapping("/list") @ResponseBody public List<User> list() { return iUserService.selectList(null); } }
package com.dyp.dyptest.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 java.io.Serializable; /** * <p> * 用户 * </p> * * @author dyp * @since 2019-07-09 */ public class User extends Model<User> { private static final long serialVersionUID = 1L; @TableId(value="id", type= IdType.AUTO) private Long id; /** * 用户名 */ private String username; /** * 创建时间 */ @TableField("create_time") private Date createTime; public Long getId() { return id; } public User setId(Long id) { this.id = id; return this; } public String getUsername() { return username; } public User setUsername(String username) { this.username = username; return this; } public Date getCreateTime() { return createTime; } public User setCreateTime(Date createTime) { this.createTime = createTime; return this; } @Override protected Serializable pkVal() { return this.id; } }
package com.dyp.dyptest.mapper; import com.dyp.dyptest.entity.User; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * 用户 Mapper 接口 * </p> * * @author dyp * @since 2019-07-09 */ public interface UserMapper extends BaseMapper<User> { }
package com.dyp.dyptest.service; import com.dyp.dyptest.entity.User; import com.baomidou.mybatisplus.service.IService; /** * <p> * 用户 服务类 * </p> * * @author dyp * @since 2019-07-09 */ public interface IUserService extends IService<User> { }
package com.dyp.dyptest.serviceImpl; import com.dyp.dyptest.entity.User; import com.dyp.dyptest.mapper.UserMapper; import com.dyp.dyptest.service.IUserService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 用户 服务实现类 * </p> * * @author dyp * @since 2019-07-09 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { }
package com.dyp.dyptest; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.dyp.dyptest.mapper") //配置mapper扫描 public class DypTestApplication { public static void main(String[] args) { SpringApplication.run(DypTestApplication.class, args); } }
GitHub 加速计划 / druid / druid
27.83 K
8.56 K
下载
阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
最近提交(Master分支:3 个月前 )
f060c270 - 7 天前
1613a765
* Improve gaussdb ddl parser
* fix temp table 8 天前
更多推荐
已为社区贡献3条内容
所有评论(0)