代码生成器心得

    技术2022-07-11  79

    本文采用springboot+mybatis-plus整合代码生成器,有需要的朋友可以根据自己需要做相应修改。

    创建springboot项目

    如何创建本文就不再赘述,简直so easy!!

    导入架包

    <!-- 代码生成器 start --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.29</version> </dependency> <!-- 代码生成器 end -->

    为何加入freemarker架包呢?因为mybatis-plus默认采用Velocity引擎,而本文采用freemarker创建,所以你懂得。可以自行选择哪种引擎框架。

    创建主类(重点)

    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * <p> * 代码生成器演示 * </p> */ public class MpGenerator { /** * <p> * 读取控制台内容 * </p> */ 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(); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("zgs"); gc.setOpen(false); // 配置xml文件生成字段映射 gc.setBaseColumnList(true); // 配置xml文件生成通用查询结果集 gc.setBaseResultMap(true); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/muxin-dev?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // pc.setModuleName(scanner("模块名")); pc.setParent("com.mnmayday.test"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! // return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() // + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; // 此处不需要模块名 return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允许生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 // templateConfig.setEntity("templates/entity.java"); //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); // 不启用lombok注解 strategy.setEntityLombokModel(false); strategy.setRestControllerStyle(true); // 是否显示表名 // strategy.entityTableFieldAnnotationEnable(true); // 公共父类 // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

    这段代码,大家可以直接上官网拷贝,根据需要自行修改,官网地址:https://mp.baomidou.com/guide/generator.html

    本文修改了几处官网推荐代码,修改如下:

    1.启用xml配置文件生成策略

    // 配置xml文件生成字段映射 gc.setBaseColumnList(true); // 配置xml文件生成通用查询结果集 gc.setBaseResultMap(true);

    效果如下,会生成如下的字段映射关系

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mnmayday.test.mapper.UsersMapper"> <!-- 通用查询映射结果 --> <resultMap id="BaseResultMap" type="com.mnmayday.test.entity.Users"> <result column="id" property="id" /> <result column="username" property="username" /> <result column="password" property="password" /> <result column="face_image" property="faceImage" /> <result column="face_image_big" property="faceImageBig" /> <result column="nickname" property="nickname" /> <result column="qrcode" property="qrcode" /> <result column="cid" property="cid" /> </resultMap> <!-- 通用查询结果列 --> <sql id="Base_Column_List"> id, username, password, face_image, face_image_big, nickname, qrcode, cid </sql> </mapper>

    2.关闭lombok注解

    // 不启用lombok注解 strategy.setEntityLombokModel(false);

    否则会在实体类标注@Lombok注解,该注解的作用是在idea中可以不用写get、set方法,eclipse目前不知道是否起作用。

    分页实现

    懒得再开一篇文章讲分页实现了,发布完以上内容,发觉少了,分页的部分,回头重新搞事。因为采用mybatis-plus代码生成器,所以不必添加额外的架包,走起!!

    配置分页实现

    import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration @MapperScan("com.mnmayday.test.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false // paginationInterceptor.setOverflow(false); // 设置最大单页限制数量,默认 500 条,-1 不受限制 // paginationInterceptor.setLimit(500); // 开启 count 的 join 优化,只针对部分 left join paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); return paginationInterceptor; } }

    这段代码同样拷贝官网推荐代码,本文采用springboot方式,官网同样推出xml配置文件的形式,有需要的可以自行选择,官网地址:https://mp.baomidou.com/guide/page.html

    实现部分

    service接口代码

    /** * <p> * 服务类 * </p> * * @author zgs * @since 2020-07-02 */ public interface IUsersService extends IService<Users> { IPage<Users> getPage(Page<Users> page, Users users); }

    service实现代码

    /** * <p> * 服务实现类 * </p> * * @author zgs * @since 2020-07-02 */ @Service public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService { @Override public IPage<Users> getPage(Page<Users> page, Users users) { page.setOptimizeCountSql(true); page.setSearchCount(true); return baseMapper.getPage(page, users); } }

    mapper代码

    /** * <p> * Mapper 接口 * </p> * * @author zgs * @since 2020-07-02 */ public interface UsersMapper extends BaseMapper<Users> { IPage<Users> getPage(Page<Users> page, Users users); }

    xml代码

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mnmayday.test.mapper.UsersMapper"> <!-- 通用查询映射结果 --> <resultMap id="BaseResultMap" type="com.mnmayday.test.entity.Users"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="password" property="password" /> <result column="face_image" property="faceImage" /> <result column="face_image_big" property="faceImageBig" /> <result column="nickname" property="nickname" /> <result column="qrcode" property="qrcode" /> <result column="cid" property="cid" /> </resultMap> <!-- 通用查询结果列 --> <sql id="Base_Column_List"> id, username, password, face_image, face_image_big, nickname, qrcode, cid </sql> <select id="getPage" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from users </select> </mapper>

    controller实现

    @RestController @RequestMapping("/users") public class UsersController { @Autowired IUsersService iUsersService; @RequestMapping("getPage") public IPage<Users> getPage() { Page<Users> page = new Page<>(1, 10); return iUsersService.getPage(page, new Users()); } }

    最后的查询结果

    end!

    Processed: 0.009, SQL: 9