MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1)引入依赖pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.2version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.3.2version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.28version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
2)新建模板文件
也可以从jar中直接获取,然后修改成自己需要的内容模板即可
本文我们使用的是freemarker模板
3)生成器代码
public class MpGenerator {
private static Logger logger = LoggerFactory.getLogger(MpGenerator.class);
private static final String PACK = "F:\\test\\";
private static final String DB_URL = "jdbc:mysql://localhost:3306/tiku?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
private static String modulesName = "告警误报记录";
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
//全局配置
GlobalConfig gc = new GlobalConfig();
gc.setBaseResultMap(true); //使用resultMap返回结果集
gc.setIdType(IdType.ASSIGN_ID); //基本的字段映射
gc.setBaseColumnList(true); //基本的sql片段
gc.setSwagger2(false); //开启Swagger2
gc.setFileOverride(true); //是否覆盖已有文件
gc.setOutputDir(PACK); //文件输出目录
gc.setAuthor("fyy"); //作者名称
gc.setOpen(false); //是否打开文件目录
gc.setEnableCache(true); //开启xml二级缓存
gc.setControllerName("%sController"); //设置controller层bean名称
gc.setServiceImplName("%sServiceImpl"); //设置server.impl层bean名称
gc.setServiceName("I%sService"); //设置server层bean名称
gc.setXmlName("%sMapper"); //设置mapper层bean名称
gc.setMapperName("%sDao"); //设置dao层bean名称
mpg.setGlobalConfig(gc);
//数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DB_URL); //数据库连接
dsc.setDriverName(DRIVER_NAME); //驱动类
dsc.setUsername(USERNAME); //数据库用户名
dsc.setPassword(PASSWORD); //数据库连接密码
mpg.setDataSource(dsc);
//包设置
PackageConfig pc = new PackageConfig();
pc.setParent("com.fyy"); //包名
pc.setEntity("model"); //pojo包
pc.setXml("mapper"); //mapper包
pc.setController("controller"); //controller包
pc.setService("service"); //service包
pc.setServiceImpl("service.impl"); //service.impl包
String models = scanner("模块名");
pc.setModuleName(models);//父包模块名
mpg.setPackageInfo(pc);
//注入初始化配置
setTemplateMapper(mpg, models);
//策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); //数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel); //数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setEntityLombokModel(true); //使用lombok
strategy.setInclude(scanner("表名")); //需要生成的表 "tbl_dept","tbl_file"
strategy.setControllerMappingHyphenStyle(true); //驼峰转连字符
strategy.setEntityColumnConstant(false); //是否生成字段常量,默认:false
strategy.setRestControllerStyle(true); //生成 @RestController 控制器
mpg.setStrategy(strategy);
//模板设置
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
TemplateConfig tc = new TemplateConfig();
tc.setController("/templates/mp/controller.java");
tc.setService("/templates/mp/service.java");
tc.setServiceImpl("/templates/mp/serviceImpl.java");
tc.setEntity("/templates/mp/entity.java");
tc.setMapper("/templates/mp/mapper.java");
tc.setXml("/templates/mp/mapper.xml");
mpg.setTemplate(tc);
mpg.execute();
}
private static void setTemplateMapper(AutoGenerator mpg, String models) {
String modulesUp = models.substring(0, 1).toUpperCase() + models.substring(1);
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("modulesName", modulesName);
map.put("modulesApi",models);
map.put("modules",modulesUp);
this.setMap(map);
}
};
mpg.setCfg(cfg);
}
}
4)测试,运行项目
依次输入项目模块名称及要生成的数据库表名称
运行结果:
5)代码查看
@Data
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Integer id;
private String name;
private String age;
private String email;
}
<mapper namespace="com.fyy.system.mapper.UserDao">
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
<resultMap id="BaseResultMap" type="com.fyy.system.model.User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
<result column="email" property="email" />
resultMap>
<sql id="Base_Column_List">
id, name, age, email
sql>
mapper>
public interface UserDao extends BaseMapper<User> {
}
public interface IUserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {
}
@RestController
@RequestMapping("/system/user")
public class UserController {
private static Logger logger = LoggerFactory.getLogger(UserController.class);
}
代码分享:SpringBoot2.x整合Mybatis Plus代码生成器