温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

更强大的 code generator 自定义工具

发布时间:2020-07-13 21:31:11 来源:网络 阅读:651 作者:北极冷冷冷 栏目:编程语言

更强大的 code generator 自定义工具
我们以前用 mybatis 的 generator 感觉很爽,通用mapper(tk.mapper) 也很爽,但是。。。


还有更爽的 就是这两种结合 并且 还可以直接生成简单的 service controller 层 还可以包含 swagger
直接上代码:
引入依赖 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">
        <modelVersion>4.0.0</modelVersion>
        <parent>
                <groupId>com.jcbjcb.tools</groupId>
                <artifactId>jcbjcb-tools</artifactId>
                <version>1.0-SNAPSHOT</version>
        </parent>
        <artifactId>jcbjcb-generator</artifactId>
        <name>jcbjcb-generator</name>
        <description>Demo project for Spring Boot</description>
        <packaging>jar</packaging>

        <properties>
                <java.version>1.8</java.version>
        </properties>

        <dependencies>
<!--        <dependency>-->
<!--            <groupId>com.jcbjcb.tools</groupId>-->
<!--            <artifactId>jcbjcb-commom</artifactId>-->
<!--            <version>${project.version}</version>-->
<!--        </dependency>-->
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                </dependency>

                <dependency>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <optional>true</optional>
                </dependency>

                <!-- 通用mapper -->
                <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper-spring-boot-starter</artifactId>
                        <version>2.1.5</version>
                </dependency>

                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-data-jpa</artifactId>
                </dependency>
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
                </dependency>
                <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.7</version>
                </dependency>
                <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper-generator</artifactId>
                        <version>1.1.5</version>
                </dependency>
                <dependency>
                        <groupId>io.springfox</groupId>
                        <artifactId>springfox-swagger2</artifactId>
                        <version>2.9.2</version>
                </dependency>
                <dependency>
                        <groupId>io.springfox</groupId>
                        <artifactId>springfox-swagger-ui</artifactId>
                        <version>2.9.2</version>
                </dependency>

                <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.15</version>
                </dependency>
                <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.1.5</version>
                </dependency>
                <dependency>
                        <groupId>org.freemarker</groupId>
                        <artifactId>freemarker</artifactId>
                        <version>2.3.28</version>
                </dependency>

        </dependencies>

        <build>
                <plugins>
                        <plugin>
                                <artifactId>maven-compiler-plugin</artifactId>
                                <configuration>
                                        <source>${java.version}</source>
                                        <target>${java.version}</target>
                                </configuration>
                        </plugin>
                        <plugin>
                                <groupId>org.mybatis.generator</groupId>
                                <artifactId>mybatis-generator-maven-plugin</artifactId>
                                <version>1.3.7</version>
                                <configuration>
                                        <configurationFile>
                                                ${basedir}/src/main/resources/generator/generatorConfig.xml
                                        </configurationFile>
                                        <overwrite>true</overwrite>
                                        <verbose>true</verbose>
                                </configuration>
                                <dependencies>
                                        <dependency>
                                                <groupId>mysql</groupId>
                                                <artifactId>mysql-connector-java</artifactId>
                                                <version>8.0.15</version>
                                        </dependency>
                                        <dependency>
                                                <groupId>tk.mybatis</groupId>
                                                <artifactId>mapper</artifactId>
                                                <version>4.1.5</version>
                                        </dependency>
                                        <dependency>
                                                <groupId>org.freemarker</groupId>
                                                <artifactId>freemarker</artifactId>
                                                <version>2.3.28</version>
                                        </dependency>
                                </dependencies>
                        </plugin>
                </plugins>
        </build>

</project>

generatorConfig.xml

<!DOCTYPE generatorConfiguration
                PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
                "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
        <properties resource="generator/config.properties"/>

        <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
                <property name="beginningDelimiter" value="`"/>
                <property name="endingDelimiter" value="`"/>

                <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
                        <property name="mappers" value="tk.mybatis.mapper.common.Mapper,tk.mybatis.mapper.common.MySqlMapper"/>
                        <!-- caseSensitive 是否区分大小写,默认值 false。如果数据库区分大小写,这里就需要配置为 true,这样当表名为 USER 时,会生成 @Table(name = "USER") 注解,否则使用小写 user 时会找不到表。 -->
<!--            <property name="caseSensitive" value="false"/>-->
                        <!-- forceAnnotation 是否强制生成注解,默认 false,如果设置为 true,不管数据库名和字段名是否一致,都会生成注解(包含 @Table 和 @Column)。 -->
<!--            <property name="forceAnnotation" value="false"/>-->
                        <!-- beginningDelimiter 和 endingDelimiter 开始和结束分隔符,对于有关键字的情况下适用。-->
<!--            <property name="beginningDelimiter" value="`"/>-->
<!--            <property name="endingDelimiter" value="`"/>-->
                        <!-- useMapperCommentGenerator 是否使用通用 Mapper 提供的注释工具,默认 true 使用,这样在生成代码时会包含字段的注释(目前只有 mysql 和 oracle 支持),设置 false 后会用默认的,或者你可以配置自己的注释插件。-->
<!--            <property name="useMapperCommentGenerator " value="true"/>-->
                        <!--            generateColumnConsts 在生成的 model中,增加字段名的常量,便于使用 Example 拼接查询条件的时候使用。-->
<!--            <property name="generateColumnConsts" value="`"/>  -->
                        <!-- lombok 增加 model 代码生成时,可以直接生成 lombok 的 @Getter@Setter@ToString@Accessors(chain = true) 四类注解, 使用者在插件配置项中增加 <property name="lombok" value="Getter,Setter,ToString,Accessors"/> 即可生成对应包含注解的 model 类。-->
<!--            <property name="lombok" value="Getter,Setter,ToString,Accessors"/>-->
                        <property name="lombok" value="Data"/>
                        <property name="swagger" value="true"/>
                </plugin>
                <!--mapper接口-->
                <plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
                        <property name="targetProject" value="src/main/java"/>
                        <property name="targetPackage" value="com.jcbjcb.tools.generator.mapper"/>
                        <property name="templatePath" value="file:src\main\resources\generator/template/mapper.ftl"/>
                        <property name="mapperSuffix" value="Mapper"/>
                        <property name="fileName" value="${tableClass.shortClassName}${mapperSuffix}.java"/>
                        <!--默认值是下面这个,可以不配置-->
                        <property name="templateFormatter"
                                            value="tk.mybatis.mapper.generator.formatter.FreemarkerTemplateFormatter"/>
                        <property name="encoding" value="UTF-8"/>

                </plugin>

                <!--输出单个文件,每个表都会生成一个对应的文件 biz-->
                <plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
                        <property name="targetProject" value="src/main/java"/>
                        <property name="targetPackage" value="com.jcbjcb.tools.generator.biz"/>
                        <property name="templatePath" value="file:src\main\resources\generator/template/biz.ftl"/>
                        <property name="mapperSuffix" value="Biz"/>
                        <property name="fileName" value="${tableClass.shortClassName}${mapperSuffix}.java"/>
                        <!--默认值是下面这个,可以不配置-->
                        <property name="templateFormatter"
                                            value="tk.mybatis.mapper.generator.formatter.FreemarkerTemplateFormatter"/>
                        <property name="encoding" value="UTF-8"/>
                </plugin>

                <!--输出单个文件,每个表都会生成一个对应的文件 controller-->
                <plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
                        <property name="targetProject" value="src/main/java"/>
                        <property name="targetPackage" value="com.jcbjcb.tools.generator.control"/>
                        <property name="templatePath" value="file:src\main\resources\generator/template/controller.ftl"/>
                        <property name="mapperSuffix" value="Controller"/>
                        <property name="fileName" value="${tableClass.shortClassName}${mapperSuffix}.java"/>
                        <!--默认值是下面这个,可以不配置-->
                        <property name="templateFormatter"
                                            value="tk.mybatis.mapper.generator.formatter.FreemarkerTemplateFormatter"/>
                        <property name="encoding" value="UTF-8"/>
                </plugin>

                <jdbcConnection driverClass="${jdbc.driverClass}"
                                                connectionURL="${jdbc.url}"
                                                userId="${jdbc.user}"
                                                password="${jdbc.password}">
                </jdbcConnection>

                <javaModelGenerator targetPackage="com.jcbjcb.tools.generator.entity"
                                                        targetProject="src/main/java"/>

                <sqlMapGenerator targetPackage="mapper"
                                                 targetProject="src/main/resources"/>

<!--        <javaClientGenerator targetPackage="com.jcbjcb.generator.mapper"-->
<!--                             targetProject="src/main/java"-->
<!--                             type="XMLMAPPER"/>-->

                <table tableName="tab_school">
                        <generatedKey column="id" sqlStatement="mysql" identity="true"/>
                </table>
        </context>
</generatorConfiguration>

config.properties

    jdbc.driverClass = com.mysql.cj.jdbc.Driver
    jdbc.url = jdbc:mysql://127.0.0.1:3306/school_score?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    jdbc.user = root
    jdbc.password = root

代码生成模板
biz.ftl

package ${package};

import com.jcbjcb.tools.common.biz.BaseBiz;
import ${package?substring(0,package?last_index_of('.'))}.mapper.${tableClass.shortClassName}Mapper;
import ${tableClass.fullClassName};
import org.springframework.stereotype.Service;

<#assign dateTime = .now>
/**
* @description ${tableClass.shortClassName}业务层
* @author  jcb
* @since  ${dateTime?string["yyyy-MM-dd HH:mm:ss"]}
*/
@Service
public class ${tableClass.shortClassName}Biz extends BaseBiz<${tableClass.shortClassName}Mapper, ${tableClass.shortClassName}> {

}

controller.ftl

package ${package};

import com.jcbjcb.tools.common.rest.BaseController;
import ${package?substring(0,package?last_index_of('.'))}.biz.${tableClass.shortClassName}Biz;
import ${tableClass.fullClassName};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

<#assign dateTime = .now>
/**
* @description ${tableClass.shortClassName}控制层
* @author  jcb
* @since  ${dateTime?string["yyyy-MM-dd HH:mm:ss"]}
*/
@RestController
@RequestMapping("/${tableClass.variableName}")
public class ${tableClass.shortClassName}Controller extends BaseController<${tableClass.shortClassName}Biz, ${tableClass.shortClassName}> {

}

mapper.ftl

package ${package};

import com.jcbjcb.tools.common.mapper.BaseMapper;
import ${tableClass.fullClassName};
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

<#assign dateTime = .now>
/**
 * @description ${tableClass.shortClassName}数据层
 * @author  jcb
 * @since  ${dateTime?string["yyyy-MM-dd HH:mm:ss"]}
*/
@Mapper
@Repository
public interface ${tableClass.shortClassName}Mapper extends BaseMapper<${tableClass.shortClassName}> {

}

基础类

BaseMapper.class

package com.jcbjcb.tools.common.mapper;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

BaseBiz.class

package com.jcbjcb.tools.common.biz;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcbjcb.tools.common.util.Query;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

public abstract class BaseBiz<M extends Mapper<T>,T> {
        @Autowired
        protected M mapper;

        public void setMapper(M mapper) {
                this.mapper = mapper;
        }

        public T selectOne(T entity) {
                return mapper.selectOne(entity);
        }

        public T selectById(Object id) {
                return mapper.selectByPrimaryKey(id);
        }

        public List<T> selectList(T entity) {
                return mapper.select(entity);
        }

        public List<T> selectListAll() {
                return mapper.selectAll();
        }

        public Long selectCount(T entity) {
                return new Long(mapper.selectCount(entity));
        }

        public void insert(T entity) {
                mapper.insert(entity);
        }

        public void insertSelective(T entity) {
                mapper.insertSelective(entity);
        }

        public void delete(T entity) {
                mapper.delete(entity);
        }

        public void deleteById(Object id) {
                mapper.deleteByPrimaryKey(id);
        }

        public void updateById(T entity) {
                mapper.updateByPrimaryKey(entity);
        }

        public void updateSelectiveById(T entity) {
                mapper.updateByPrimaryKeySelective(entity);

        }

        public List<T> selectByExample(Object example) {
                return mapper.selectByExample(example);
        }

        public int selectCountByExample(Object example) {
                return mapper.selectCountByExample(example);
        }

        public PageInfo<T> selectByQuery(Query query) {
                Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
                Example example = new Example(clazz);
                if(query.entrySet().size()>0) {
                        Example.Criteria criteria = example.createCriteria();
                        for (Map.Entry<String, Object> entry : query.entrySet()) {
                                criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                        }
                }
                Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
                List<T> list = mapper.selectByExample(example);
                return new PageInfo<T>(list);
        }
}

BaseController.class

package com.jcbjcb.tools.common.rest;

import com.github.pagehelper.PageInfo;
import com.jcbjcb.tools.common.biz.BaseBiz;
import com.jcbjcb.tools.common.util.ObjectRestResponse;
import com.jcbjcb.tools.common.util.Query;
import com.jcbjcb.tools.common.util.TableRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

public class BaseController<Biz extends BaseBiz,Entity> {
        @Autowired
        protected HttpServletRequest request;
        @Autowired
        protected Biz baseBiz;

        @RequestMapping(value = "",method = RequestMethod.POST)
        @ResponseBody
        public ObjectRestResponse<Entity> add(@RequestBody Entity entity){
                baseBiz.insertSelective(entity);
                return new ObjectRestResponse<>(entity);
        }

        @RequestMapping(value = "/{id}",method = RequestMethod.GET)
        @ResponseBody
        public ObjectRestResponse<Entity> get(@PathVariable int id){
                ObjectRestResponse<Entity> entityObjectRestResponse = new ObjectRestResponse<>();
                Object o = baseBiz.selectById(id);
                entityObjectRestResponse.setData((Entity)o);
                return entityObjectRestResponse;
        }

        @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
        @ResponseBody
        public ObjectRestResponse<Entity> update(@RequestBody Entity entity){
                baseBiz.updateSelectiveById(entity);
                return new ObjectRestResponse<>(entity);
        }
        @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
        @ResponseBody
        public ObjectRestResponse<Entity> remove(@PathVariable int id){
                baseBiz.deleteById(id);
                return new ObjectRestResponse<>();
        }

        @RequestMapping(value = "/all",method = RequestMethod.GET)
        @ResponseBody
        public List<Entity> all(){
                return baseBiz.selectListAll();
        }

        @RequestMapping(value = "/page",method = RequestMethod.GET)
        @ResponseBody
        public TableRestResponse<Entity> list(@RequestParam Map<String, Object> params){
                //查询列表数据
                Query query = new Query(params);
                PageInfo<Entity> pageInfo = baseBiz.selectByQuery(query);
                return new TableRestResponse<>(pageInfo.getList());
        }
}

最后执行

mvn mybatis-generator:generate 生成代码

或者在idea上mvn插件里面生成


具体代码在 github 上
https://github.com/jcbjcb/jcbjcb-tools

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI