本文主要介绍如何在IDEA中,编写代码连接数据库生成对应的POJO、Mapper、Service、Controller
在实际开发中,设计完数据库后,不可避免需要创建数据库表对应的POJO,一个个照着数据库表和字段创建POJO,不仅麻烦,还容易出错!
生成数据库表对应的POJO,有两种方式:
数据库表右键->tools
一些列操作下来,直接生成POJO本文主要讲解第2种方式,代码生成器
如下图,controller、mapper、model、service
代码都是最后的生成结果,项目整体框架如下:
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">
<parent>
<artifactId>spring-learn</artifactId>
<groupId>org.ym</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>learn-common-generate</artifactId>
<dependencies>
<!-- 日志相关配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
配置数据库和策略
package com.ym.learn.generate;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import javax.sql.DataSource;
import java.util.Arrays;
import static com.ym.learn.generate.CodeGenerateConstant.*;
/**
* @Author: Yangmiao
* @Date: 2023/5/29 20:18
* @Desc:
*/
public class CodeConfig {
/**
* 数据库配置
* @param databaseName
* @return
*/
public static DataSourceConfig getDataSource(String databaseName){
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/" + databaseName
+ "?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8");
dsc.setUsername(DB_USERNAME);
dsc.setPassword(DB_PASSWORD);
dsc.setDriverName(DB_DRIVER_CLASS_NAME);
return dsc;
}
/**
* 策略配置
* @param tableArrays 数据库表集合
* @param pc
* @return
*/
public static StrategyConfig getStrategyConfig(String []tableArrays, PackageConfig pc){
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(tableArrays);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
// Boolean类型字段是否移除is前缀处理
strategy.setEntityBooleanColumnRemoveIsPrefix(true);
strategy.setRestControllerStyle(true);
// 自动填充字段配置
strategy.setTableFillList(Arrays.asList(
new TableFill("create_date", FieldFill.INSERT),
new TableFill("change_date", FieldFill.INSERT_UPDATE),
new TableFill("modify_date", FieldFill.UPDATE)
));
return strategy;
}
}
package com.ym.learn.generate;
/**
* @Author: Yangmiao
* @Date: 2023/5/29 20:02
* @Desc: 常量信息
*/
public class CodeGenerateConstant {
/**
* 数据库用户名
*/
public static final String DB_USERNAME = "root";
/**
* 数据库密码
*/
public static final String DB_PASSWORD = "123456";
/**
* 数据库驱动名称
*/
public static final String DB_DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
}
配置数据库的基本信息、包路径信息、数据库表信息,一键运行,刷新代码,就会自动生成pojo等。
package com.ym.learn.generate;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
* @Author: Yangmiao
* @Date: 2023/5/29 19:59
* @Desc: 模板代码生成器
*/
public class CodeGenerate {
/**
* 数据库表
*/
private static final String[] TABLE_NAMES = new String[]{
"media_files"
};
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Velocity
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setFileOverride(true);
//生成路径
gc.setOutputDir(System.getProperty("user.dir") + "/learn-common/learn-common-generate/src/main/java");
gc.setAuthor("yangmiao");
gc.setOpen(false);
gc.setSwagger2(false);
gc.setServiceName("%sService");
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
mpg.setGlobalConfig(gc);
DataSourceConfig dataSource = CodeConfig.getDataSource("learn-spring");
mpg.setDataSource(dataSource);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("generate");
pc.setParent("com.ym.learn.generate");
pc.setServiceImpl("service.impl");
pc.setXml("mapper");
pc.setEntity("model.po");
mpg.setPackageInfo(pc);
// 设置模板
TemplateConfig tc = new TemplateConfig();
mpg.setTemplate(tc);
// 设置策略
StrategyConfig strategyConfig = CodeConfig.getStrategyConfig(TABLE_NAMES, pc);
mpg.setStrategy(strategyConfig);
mpg.execute();
}
}