之前带来过SpringBoot整合thymeleaf+代码生成器(最全,最详细),这篇主要是生成dao层,并没有生成service和web。本篇博客直接生成MVC三层代码,并使用mybatisPlus简化实体XML的配置。
推荐直接上我的git下载源码,麻烦给个星星,谢谢啦。
4.0.0
com.warrior
ETH
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.0.BUILD-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
com.baomidou
mybatisplus-spring-boot-starter
1.0.4
com.baomidou
mybatis-plus
2.0.7
org.apache.velocity
velocity
1.7
org.freemarker
freemarker
2.3.28
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
com.alibaba
druid
1.1.9
org.projectlombok
lombok
0.10.1
provided
org.springframework.boot
spring-boot-maven-plugin
src/main/resources
spring-snapshots
http://repo.spring.io/snapshot
true
spring-milestones
http://repo.spring.io/milestone
spring-snapshots
http://repo.spring.io/snapshot
spring-milestones
http://repo.spring.io/milestone
server.port=666
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
#mybatis plus 设置
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
mybatis-plus.typeAliasesPackage=com.warrior.entity
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus.global-config.id-type=0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
mybatis-plus.global-config.field-strategy=2
#驼峰下划线转换
mybatis-plus.global-config.db-column-underline=true
#刷新mapper 调试神器
mybatis-plus.global-config.refresh-mapper=true
#数据库大写下划线转换
#mybatis-plus.global-config.capital-mode=true
#逻辑删除配置
mybatis-plus.global-config.logic-delete-value=0
mybatis-plus.global-config.logic-not-delete-value=1
#默认启用开发环境配置
spring.profiles.active=dev
#启用生产环境配置
#spring.profiles.active=pro
DataSourceConfig
package com.warrior.config;
import javax.sql.DataSource;
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 com.alibaba.druid.pool.DruidDataSource;
/**
* 数据源配置
*/
@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());
}
}
MybatisPlusConfig
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.warrior.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();
}
}
UserController(代码生成出来的,不包含方法体)
package com.warrior.controler;
import com.warrior.entity.User;
import com.warrior.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
*
* 前端控制器
*
*
* @author hjh
* @since 2019-07-29
*/
@Controller
@RequestMapping("/warrior/user")
public class UserController {
@Autowired
private IUserService iUserService;
@RequestMapping("insert")
@ResponseBody
private String insert(User user) {
return iUserService.insertByUser(user);
}
@RequestMapping("update")
@ResponseBody
private String update(User user) {
return iUserService.updateByUser(user);
}
@RequestMapping("list")
private String list(User user, Model model) {
List users = iUserService.selectList(user);
model.addAttribute("userList", users);
return "userList";
}
@RequestMapping("delete")
@ResponseBody
private String delete(User user) {
return iUserService.deleteByUser(user);
}
}
User(代码生成出来的,不包含方法体)
package com.warrior.entity;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import java.io.Serializable;
/**
*
*
*
*
* @author hjh
* @since 2019-07-29
*/
public class User extends Model {
private static final long serialVersionUID = 1L;
@TableId(value="id", type= IdType.AUTO)
private Integer id;
private String name;
@TableField("class_name")
private String className;
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 String getClassName() {
return className;
}
public User setClassName(String className) {
this.className = className;
return this;
}
@Override
protected Serializable pkVal() {
return this.id;
}
}
UserMapper(代码生成出来的,不包含方法体)
package com.warrior.entity;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import java.io.Serializable;
/**
*
*
*
*
* @author hjh
* @since 2019-07-29
*/
public class User extends Model {
private static final long serialVersionUID = 1L;
@TableId(value="id", type= IdType.AUTO)
private Integer id;
private String name;
@TableField("class_name")
private String className;
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 String getClassName() {
return className;
}
public User setClassName(String className) {
this.className = className;
return this;
}
@Override
protected Serializable pkVal() {
return this.id;
}
}
IUserService(代码生成出来的,不包含方法体)
package com.warrior.service;
import com.baomidou.mybatisplus.service.IService;
import com.warrior.entity.User;
import java.util.List;
/**
*
* 服务类
*
*
* @author hjh
* @since 2019-07-29
*/
public interface IUserService extends IService {
String insertByUser(User user);
String updateByUser(User user);
String deleteByUser(User user);
List selectList(User user);
}
UserServiceImpl(代码生成出来的,不包含方法体)
package com.warrior.serviceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.warrior.entity.User;
import com.warrior.mapper.UserMapper;
import com.warrior.service.IUserService;
import com.warrior.util.EmptyUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* 服务实现类
*
*
* @author hjh
* @since 2019-07-29
*/
@Service
public class UserServiceImpl extends ServiceImpl implements IUserService {
@Override
public String insertByUser(User user) {
Integer insert = this.baseMapper.insert(user);
return EmptyUtils.isNotEmpty(insert) && insert == 1 ? "SUCCESS" : "FALID";
}
@Override
public String updateByUser(User user) {
Integer updateAllColumnById = this.baseMapper.updateById(user);
return EmptyUtils.isNotEmpty(updateAllColumnById) && updateAllColumnById == 1 ? "SUCCESS" : "FALID";
}
@Override
public String deleteByUser(User user) {
EntityWrapper userEntityWrapper = new EntityWrapper<>();
userEntityWrapper.eq("id",user.getId());
Integer delete = this.baseMapper.delete(userEntityWrapper);
return EmptyUtils.isNotEmpty(delete) && delete == 1 ? "SUCCESS" : "FALID";
}
@Override
public List selectList(User user) {
EntityWrapper userEntityWrapper = new EntityWrapper<>();
if(EmptyUtils.isNotEmpty(user)){
String className = user.getClassName();
Integer id = user.getId();
String name = user.getName();
if(EmptyUtils.isNotEmpty(className)){
userEntityWrapper.eq("class_name",className);
}
if(EmptyUtils.isNotEmpty(id)){
userEntityWrapper.eq("id",id);
}
if(EmptyUtils.isNotEmpty(name)){
userEntityWrapper.eq("name",name);
}
}
return this.baseMapper.selectList(userEntityWrapper);
}
}
EmptyUtils(自定义判空工具类,不是代码生成的!)
package com.warrior.util;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
/**
* 判空工具类
*
* @author hjh
* @date 2019/07/23
*/
public class EmptyUtils {
/**
* 判断对象是否为空
*
* @param obj 对象
* @return {@code true}: 为空
{@code false}: 不为空
*/
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof String && obj.toString().trim().length() == 0) {
return true;
}
if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
return true;
}
if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
return true;
}
if (obj instanceof Map && ((Map) obj).isEmpty()) {
return true;
}
return false;
}
/**
* 判断对象是否非空
*
* @param obj 对象
* @return {@code true}: 非空
{@code false}: 空
*/
public static boolean isNotEmpty(Object obj) {
return !isEmpty(obj);
}
}
Application(这个是Spring项目启动器,不是代码生成器生成的!)
package com.warrior;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.warrior.mapper") //配置mapper扫描
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
userMapper.xml
id, name, class_name AS className
配置文件在上面这里就不再复制了,pro为测试环境的配置,我只写了本地的(dev)
MpGenerator(运行main方法,执行代码生成器)
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 dirPath = "E://";//生成的路径,最好不要写项目具体位置,不然会删除所有代码,自己复制粘贴过去最好
/**
*
* MySQL 生成演示
*
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(dirPath);
gc.setAuthor("hjh");//设置作者
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("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8");
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.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");
pc.setModuleName("warrior");
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 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 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("abc"));
}
}
本次的代码生成器会覆盖掉代码(web,service),所以不建议直接生成在项目下,使用步骤:
1:生成代码,默认为E盘根目录;
2:复制粘贴需要的pojo,mapper,mapper.xml到项目的包下;
3:MyBatis-Plus包涵了一系列封装方法,具体使用请参考Mybatis-plus官网或者自行百度。