mybatisplus代码生成器使用(java代码生成工具)

前言

在日常的软件开发中,程序员往往需要花费大量的时间写CRUD,不仅枯燥效率低,而且每个人的代码风格不统一。MyBatis-Plus 代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块及前端页面的代码,极大的提升了开发效率。

项目介绍

本项目将以springboot用演示,前端使用freemaker,数据库持久层用mybatis(考虑到mybatis的使用还是最普遍的,就没有用jpa和mybatisplus),通过Velocity模板引擎配置各模块的文件模板,通过mybatis-plus代码生成器连接mysql,用商品表为例生成各模块的代码和前端页面。(本项目只演示分页查询和导出功能)。

实战数据库脚本

创建一张商品表test_goods

CREATETABLE`test_goods`(`id`bigint(20)DEFAULTNULLCOMMENT’id’,`goods_sn`varchar(45)DEFAULTNULLCOMMENT’商品编码’,`name`varchar(255)DEFAULTNULLCOMMENT’商品名称’,`title`varchar(80)DEFAULTNULLCOMMENT’标题’,`price`decimal(10,2)DEFAULTNULLCOMMENT’售价’,`status`int(2)DEFAULTNULLCOMMENT’商品状态’,`sale_count`int(11)DEFAULTNULLCOMMENT’销量’,`create_date`datetimeDEFAULTNULLCOMMENT’创建时间’,`modify_date`datetimeDEFAULTNULLCOMMENT’修改时间’)ENGINE=InnoDBDEFAULTCHARSET=utf8maven依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>2.1.4</version></dependency><!–aspectj–><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><scope>provided</scope></dependency><!–es–><!–lombok简化get/set方法–><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.10</version><scope>provided</scope></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!–csv导出用到–><dependency><groupId>com.opencsv</groupId><artifactId>opencsv</artifactId><version>3.8</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency></dependencies>配置文件mybatis:mapper-locations:classpath:mybatis/*Mapper.xmltype-aliases-package:com.lzn.mybatisplus.codegenerator.entityspring:datasource:username:rootpassword:123qweurl:jdbc:mysql://192.168.0.1:3306/myProject?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCdriver-class-name:com.mysql.jdbc.Driverredis:host:192.168.0.1password:1234qwerport:6379freemarker:template-loader-path:classpath:/templates/pages/cache:falsecharset:UTF-8check-template-location:truecontent-type:text/htmlexpose-request-attributes:trueexpose-session-attributes:truesuffix:.ftl模板文件

实体类模板(entity.java.vm)

package${package.Entity};importjava.math.BigDecimal;importjava.util.Date;importlombok.Getter;importlombok.Setter;importlombok.ToString;/***数据库表名${table.name}**@author${author}*@date${date}*/@Getter@Setter@ToStringpublicclass${table.entityName}{#foreach($fieldin${table.fields})/***数据库字段名${field.name}类型${field.type}*/private${field.propertyType}${field.propertyName};#end}

Controller模板(controller.java.vm)

package${package.Controller};import${package.Entity}.${entity};import${package.Service}.${table.serviceName};importcom.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;importcom.lzn.mybatisplus.codegenerator.export.${table.entityName}ExportService;importcom.lzn.mybatisplus.codegenerator.utils.entity.*;importcom.lzn.mybatisplus.codegenerator.utils.export.*;importorg.apache.commons.beanutils.ConvertUtils;importcom.lzn.mybatisplus.codegenerator.utils.ParameterUtil;importcom.lzn.mybatisplus.codegenerator.utils.entity.GridDataModel;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.*;importjavax.annotation.Resource;importjavax.servlet.ServletRequest;importjavax.servlet.http.HttpServletRequest;importjava.util.List;importjava.util.Map;/***<p>*${tablecomment}前端控制器*</p>**@author${author}*@since${date}*/@Controller@RequestMapping(value=”/admin/${table.entityPath}”)publicclass${table.controllerName}{privatestaticLoggerlogger=LoggerFactory.getLogger(${table.controllerName}.class);@Resourceprivate${entity}Service${table.entityPath}Service;@RequestMapping(value=”list”,method=RequestMethod.GET)publicStringlist(Modelmodel){return”/admin/${cfg.pageDirName}/list”;}@RequestMapping(value=”searchList”,method=RequestMethod.POST)@ResponseBody@ExportMethod(serviceClass=${entity}ExportService.class,memo=”明细导出”)publicStringsearchList(ServletRequestrequest,@ModelAttribute(“page”)OmuiPagepage){try{Map<String,Object>searchParam=ParameterUtil.getParametersStartingWith(request,”filter_”);GridDataModel<${entity}VO>gd=${table.entityPath}Service.findByPage(searchParam,page);returnJsonMapper.nonDefaultMapper().toJson(gd);}catch(Exceptione){logger.error(“查询出错了”,e);returnJsonMapper.nonDefaultMapper().toJson(newResp(“false”,e.getMessage()));}}}

Service类模板(service.java.vm)

package${package.Service};importorg.springframework.stereotype.Service;importcom.lzn.mybatisplus.codegenerator.dao.${table.mapperName};importcom.lzn.mybatisplus.codegenerator.utils.entity.GridDataModel;importcom.lzn.mybatisplus.codegenerator.utils.entity.OmuiPage;importcom.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;importjavax.annotation.Resource;importjava.math.BigDecimal;importjava.text.DateFormat;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.*;/***<p>*$!{tablecomment}服务类*</p>**@author${author}*@since${date}*/@Servicepublicclass${table.serviceName}{@Resourceprivate${table.mapperName}${table.entityPath}Dao;/***分页查询**/publicGridDataModel<${table.entityName}VO>findByPage(Map<String,Object>searchParams,OmuiPagepage){GridDataModel<${table.entityName}VO>gm=newGridDataModel<${table.entityName}VO>();searchParams.put(“start”,page.getStart());searchParams.put(“limit”,page.getLimit());longcount=${table.entityPath}Dao.countForPage(searchParams);List<${table.entityName}VO>list=${table.entityPath}Dao.listForPage(searchParams);gm.setTotal(count);gm.setRows(list);returngm;}}

Dao类模板(dao.java.vm)

package${package.Mapper};importcom.lzn.mybatisplus.codegenerator.entity.${table.entityName};importcom.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;importjava.util.List;importjava.util.Map;publicinterface${table.mapperName}{/***根据主键删除数据库的记录,${table.name}*/intdeleteByPrimaryKey(Longid);/***新写入数据库记录,${table.name}*/intinsert(${table.entityName}record);/***根据指定主键获取一条数据库记录,${table.name}*/${table.entityName}selectByPrimaryKey(Longid);/***根据主键来更新符合条件的数据库记录,${table.name}*/intupdateByPrimaryKey(${table.entityName}record);/***根据条件分页查询**/List<${table.entityName}VO>listForPage(Map<String,Object>searchMap);/***根据条件分页查询(计数)**/longcountForPage(Map<String,Object>searchMap);}

Mapper.xml模板(mapper.xml.vm)

<?xmlversion=”1.0″encoding=”UTF-8″?><!DOCTYPEmapperPUBLIC”-//mybatis.org//DTDMapper3.0//EN””http://mybatis.org/dtd/mybatis-3-mapper.dtd”><mappernamespace=”${package.Mapper}.${table.mapperName}”>#if(${baseResultMap})<!–通用查询映射结果–><resultMapid=”BaseResultMap”type=”${package.Entity}.${entity}”>#foreach($fieldin${table.fields})#if(${field.keyFlag})##生成主键排在第一位<idcolumn=”${field.name}”property=”${field.propertyName}”/>#end#end#foreach($fieldin${table.commonFields})##生成公共字段<resultcolumn=”${field.name}”property=”${field.propertyName}”/>#end#foreach($fieldin${table.fields})#if(!${field.keyFlag})##生成普通字段<resultcolumn=”${field.name}”property=”${field.propertyName}”/>#end#end</resultMap>#end#if(${baseColumnList})<!–通用查询结果列–><sqlid=”Base_Column_List”>#foreach($fieldin${table.commonFields})#if(${field.name}==${field.propertyName})${field.name}#else${field.name}AS${field.propertyName}#end,#end${table.fieldNames}</sql>#end<deleteid=”deleteByPrimaryKey”parameterType=”java.lang.Long”><!—->deletefrom${table.name}where#foreach($fieldin${table.fields})#if(${field.keyFlag})##主键${field.name}=#{${field.propertyName}}#end#end</delete><insertid=”insert”parameterType=”${package.Entity}.${entity}”><!—-><selectKeykeyProperty=”id”order=”AFTER”resultType=”java.lang.Long”>SELECTLAST_INSERT_ID()</selectKey>insertinto${table.name}(#foreach($fieldin${table.fields})#if(!${field.keyFlag})##生成普通字段${field.name}#if($foreach.hasNext),#end#end#end)values(#foreach($fieldin${table.fields})#if(!${field.keyFlag})##生成普通字段#{${field.propertyName}}#if($foreach.hasNext),#end#end#end)</insert><updateid=”updateByPrimaryKey”parameterType=”${package.Entity}.${entity}”><!—->update${table.name}set#foreach($fieldin${table.fields})#if(!${field.keyFlag})##生成普通字段${field.name}=#{${field.propertyName}}#if($foreach.hasNext),#end#end#endwhere#foreach($fieldin${table.fields})#if(${field.keyFlag})id=#{${field.name}}#end#end</update><selectid=”selectByPrimaryKey”parameterType=”java.lang.Long”resultMap=”BaseResultMap”><!—->select<includerefid=”Base_Column_List”/>from${table.name}whereid=#{id}</select><selectid=”countForPage”parameterType=”map”resultType=”Long”><!—->selectcount(*)from${table.name}where1=1<iftest=”beginDate!=nullandbeginDate!=””>andcreate_date<![CDATA[>=]]>#{beginDate}</if><iftest=”endDate!=nullandendDate!=””>andcreate_date<![CDATA[<=]]>#{endDate}</if></select><selectid=”listForPage”parameterType=”map”resultType=”com.lzn.mybatisplus.codegenerator.export.${table.entityName}VO”><!—->select<includerefid=”Base_Column_List”/>from${table.name}where1=1<iftest=”beginDate!=nullandbeginDate!=””>andcreate_date<![CDATA[>=]]>#{beginDate}</if><iftest=”endDate!=nullandendDate!=””>andcreate_date<![CDATA[<=]]>#{endDate}</if>limit#{start},#{limit}</select></mapper>

前端页面list.ftl模板(list.ftl.vm)

执行代码生成器的Main方法

mybatisplus代码生成器使用(java代码生成工具)

执行代码后,在对应的目录自动生成了文件

启动项目

并访问列表页路径 http://localhost:8080/admin/goods/list

总结

本文为项目自动生成前后端代码提供了思路:我们可以为项目的增删改查业务编写一套规范的代码,以此编写代码模板,后续通过代码生成器,通过数据库的一张表可快速生成前后端代码,提高项目组的开发效率。

代码

https://github.com/pengziliu/GitHub-code-practice

这个项目包含很多轮子实例,每个实例都配有技术文章。

觉得不错可以给个Star哦~

热门内容:

一个注解搞定 SpringBoot 接口防刷,还有谁不会?

为什么强烈推荐 Java 程序员使用 Google Guava 编程!蚂蚁金服开源增强版 Spring Boot 的研发框架!@Autowire和@Resource注解使用的正确姿势,别再用错的了!!再见了,收费的 Navicat!

发表评论

登录后才能评论