MybatisPlus代码生成器+代码模板Freemark最新最详细亲妈式版本

基本架构

在这里插入图片描述

相关依赖包

 <properties>
    <!--mybatis-plus版本-->
    <mybatis-plus-boot-starter.version>3.2.0</mybatis-plus-boot-starter.version>
    <!--mybatis-plus代码生成器引擎-->
    <mybatis-plus-generator.version>3.3.1.tmp</mybatis-plus-generator.version>
    </properties>

    <dependencies>   <!--springboot关于mybatis-plus-->
        <dependency>

            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>

        <!--代码生成器模板引擎 相关依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-generator.version}</version>
        </dependency>

        <!--MySQL支持-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl</artifactId>
            <version>3.3.2.RELEASE</version>
        </dependency>

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

CodeGenerator(提示不需要动这个代码后面有配置)

package com.song.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import utils.EmptyUtil;


import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @Description:代码生成器
 */
public class CodeGenerator {

    public static void autoGenerator(){

        //用来获取Mybatis-Plus.properties文件的配置信息
        final ResourceBundle rb = ResourceBundle.getBundle("mybatis-plus-generrator");

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath =rb.getString("projectPath");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(rb.getString("author"));
        gc.setOpen(false);
        gc.setIdType(IdType.ID_WORKER);
        //        gc.setBaseColumnList(true);
        //开启Xml属性名映射
        gc.setBaseResultMap(true);
        //将iservice前缀 i去掉
        gc.setServiceName("%sService");
        //关闭文件覆盖
        gc.setFileOverride(false);
        //指定时间处理类型
        gc.setDateType(DateType.ONLY_DATE);
         //实体属性 Swagger2 注解
         gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(rb.getString("url"));
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(rb.getString("userName"));
        dsc.setPassword(rb.getString("password"));
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(rb.getString("moduleName"));
        pc.setParent(rb.getString("parent"));
        pc.setController("web");
        //pc.setService("Service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("pojo");
        pc.setMapper("mapper");
        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()+"/sqlmap"
//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        if ("true".equals(rb.getString("entity"))){
            String entityFtlPath = rb.getString("entity.ftl.path");
            if (!EmptyUtil.isNullOrEmpty(entityFtlPath)){
                templateConfig.setEntity(entityFtlPath);
            }
        }else {
            templateConfig.setEntity(null);
        }

        if ("true".equals(rb.getString("mapper"))){
            String mapperFtlPath = rb.getString("mapper.ftl.path");
            if (!EmptyUtil.isNullOrEmpty(mapperFtlPath)){
                templateConfig.setMapper(mapperFtlPath);
            }
        }else {
            templateConfig.setMapper(null);
        }

        if ("true".equals(rb.getString("service"))){
            String serviceFtlPath = rb.getString("service.ftl.path");
            if (!EmptyUtil.isNullOrEmpty(serviceFtlPath)){
                templateConfig.setService(serviceFtlPath);
            }
        }else {
            templateConfig.setService(null);
        }

        if ("true".equals(rb.getString("serviceImp"))){
            String serviceImpFtlPath = rb.getString("serviceImp.ftl.path");
            if (!EmptyUtil.isNullOrEmpty(serviceImpFtlPath)){
                templateConfig.setServiceImpl(serviceImpFtlPath);
            }
        }else {
            templateConfig.setServiceImpl(null);
        }

        if ("true".equals(rb.getString("controller"))){
            String controllerFtlPath = rb.getString("controller.ftl.path");
            if (!EmptyUtil.isNullOrEmpty(controllerFtlPath)){
                templateConfig.setController(controllerFtlPath);
            }
        }else {
            templateConfig.setController(null);
        }
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

//        // 策略配置
//        StrategyConfig strategy = new StrategyConfig();
//        strategy.setNaming(NamingStrategy.underline_to_camel);
//        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.heima.springboot.basic.BasicPojo");
//        strategy.setEntityLombokModel(true);
//        strategy.setRestControllerStyle(true);
//        // 写于父类中的公共字段
//        String[] SuperEntityColumns =new String[]{"id","created_time","updated_time"};
//        strategy.setSuperEntityColumns(SuperEntityColumns);
//        strategy.setInclude(rb.getString("tableName").split(","));
//        strategy.setControllerMappingHyphenStyle(true);
//        String tablePrefix = rb.getString("tablePrefix");
//        if (tablePrefix!=null){
//            strategy.setTablePrefix(tablePrefix);
//        }
//        mpg.setStrategy(strategy);
//        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
//        mpg.execute();
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(rb.getString("tableName").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        String tablePrefix = rb.getString("tablePrefix");
        if (tablePrefix!=null){
            strategy.setTablePrefix(tablePrefix);
        }




        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();

    }
}

EmptyUtil

package utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description 判断对象是否为空的工具类
 */
public abstract class EmptyUtil {

	/**
	 *
	 * @方法名:对于String类型的非空判断
	 * @功能说明:对于String类型的非空判断

	 */
	public static boolean isNullOrEmpty(String str) {
		if (str == null || "".equals(str.trim()) || "null".equalsIgnoreCase(str.trim()) || "undefined".equalsIgnoreCase(str.trim())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * @方法名:对于StringBuffer类型的非空判断
	 * @功能说明:对于StringBuffer类型的非空判断

	 * @return boolean true-为空,false-不为空
	 */
	public static boolean isNullOrEmpty(StringBuffer str) {
		return (str == null || str.length() == 0);
	}

	/**
	 *
	 * @方法名:对于string数组类型的非空判断
	 * @功能说明:对于string数组类型的非空判断
	 * @return boolean true-为空,false-不为空
	 */
	public static boolean isNullOrEmpty(String[] str) {
		if (str == null || str.length == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * @方法名:对于Object类型的非空判断
	 * @功能说明:对于Object类型的非空判断
	 * @return boolean true-为空,false-不为空
	 */
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null || "".equals(obj)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * @方法名:对于Object数组类型的非空判断
	 * @功能说明:对于Object数组类型的非空判断
	 * @return boolean true-为空,false-不为空
	 */
	public static boolean isNullOrEmpty(Object[] obj) {
		if (obj == null || obj.length == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * @方法名:对于Collection类型的非空判断
	 * @功能说明:对于Collection类型的非空判断
	 * @return boolean true-为空,false-不为空
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNullOrEmpty(Collection collection) {
		if (collection == null || collection.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @方法名:对于Map类型的非空判断
	 * @功能说明:对于Map类型的非空判断
	 * @return boolean true-为空,false-不为空
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNullOrEmpty( Map map) {
		if (map == null || map.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * @方法名:removeNullUnit
	 * @功能说明: 删除集合中的空元素
	 * @return
	 */
	public static <T> List<T> removeNullUnit(List<T> xllxList) {
		List<T> need = new ArrayList<T>();
		for (int i = 0; i < xllxList.size(); i++) {
			if (!isNullOrEmpty(xllxList.get(i))) {
				need.add(xllxList.get(i));
			}
		}
		return need;
	}

}

mybatis-plus-generrator.properties

这一块里面主要修改你的数据库地址和包名以及对应的表名

#数据库地址
url=jdbc:mysql://127.0.0.1:3306/***?useUnicode=true&useSSL=false&characterEncoding=utf8
#数据库用户
userName=root
#密码
password=
#当前路径就是你的需要导出生成的路径
projectPath=绝对路径
#不需要修改
author=Admin
#父包
parent=com.alibaba
#包名
moduleName=admin
#表名前缀,看需求是否需要删除,默认不删除
tablePrefix =
#Navicat对应db下的所有表名  需要修改
tableName=ad_vistor_statistics,ad_user_role,ad_user_opertion,ad_user_login,ad_user_equipment,ad_user,ad_strategy_group,ad_sensitive,ad_role_auth,ad_role,ad_recommend_strategy,ad_menu,ad_label,ad_function,ad_channel_label,ad_channel,ad_article_statistics
#不需要修改
entity=true
entity.ftl.path=/templates/entity.java
mapper=true
mapper.ftl.path=/templates/mapper.java
service=true
service.ftl.path=/templates/service.java
serviceImp=true
serviceImp.ftl.path=/templates/serviceImpl.java
controller=true
controller.ftl.path=/templates/controller.java

test

package com.itheima.boot;

import com.song.config.CodeGenerator;

/**
 * @param
 * @Description
 * @Version v1.0
 */

public class test {
    public static void main(String[] args) {
        CodeGenerator.autoGenerator();
    }
}

所有freemark模板

Controller层

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>

/**
 * @Description:${table.comment!} 前端控制器
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

}
</#if>

entity层

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
<#--import lombok.Builder;-->
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldNameConstants;
</#if>

/**
 * @Description:${table.comment!}
 */
<#if entityLombokModel>
@Data
@NoArgsConstructor
@FieldNameConstants
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
    <#else>
@EqualsAndHashCode(callSuper = false)
    </#if>
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>

<#if entitySerialVersionUID>
    private static final long serialVersionUID = 1L;
</#if>

<#--    @Builder-->
<#--    public ${entity}(Long id,<#list table.fields as field>${field.propertyType} ${field.propertyName}<#if field_has_next>,</#if></#list>){-->
<#--        super(id);-->
<#--        <#list table.fields as field>-->
<#--        this.${field.propertyName}=${field.propertyName};-->
<#--        </#list>-->
<#--    }-->
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.comment!?length gt 0>
        <#if swagger2>
    @ApiModelProperty(value = "${field.comment}")
        <#else>
    /**
     * ${field.comment}
     */
        </#if>
    </#if>
    <#if field.keyFlag>
        <#-- 主键 -->
        <#if field.keyIdentityFlag>
    @TableId(value = "${field.name}", type = IdType.AUTO)
        <#elseif idType??>
    @TableId(value = "${field.name}", type = IdType.${idType})
        <#elseif field.convert>
    @TableId("${field.name}")
        </#if>
        <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
        <#if field.convert>
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
        <#else>
    @TableField(fill = FieldFill.${field.fill})
        </#if>
    <#elseif field.convert>
    @TableField("${field.name}")
    </#if>
    <#-- 乐观锁注解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
    <#-- 逻辑删除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循环遍历  ---------->

<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
    public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }

    <#if entityBuilderModel>
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
    <#else>
    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
    </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if entityBuilderModel>
        return this;
        </#if>
    }
    </#list>
</#if>

<#if entityColumnConstant>
    <#list table.fields as field>
    public static final String ${field.name?upper_case} = "${field.name}";

    </#list>
</#if>
<#if activeRecord>
    @Override
    protected Serializable pkVal() {
    <#if keyPropertyName??>
        return this.${keyPropertyName};
    <#else>
        return null;
    </#if>
    }

</#if>
<#if !entityLombokModel>
    @Override
    public String toString() {
        return "${entity}{" +
    <#list table.fields as field>
        <#if field_index==0>
            "${field.propertyName}=" + ${field.propertyName} +
        <#else>
            ", ${field.propertyName}=" + ${field.propertyName} +
        </#if>
    </#list>
        "}";
    }
</#if>
}

mapper层

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
 * @Description:${table.comment!}Mapper接口
 */
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
</#if>

mapper.xml.ftl

<?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="${package.Mapper}.${table.mapperName}">

<#if enableCache>
    <!-- 开启二级缓存 -->
    <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

</#if>
<#if baseResultMap>
    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主键排在第一位-->
        <id column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
<#list table.commonFields as field><#--生成公共字段 -->
    <result column="${field.name}" property="${field.propertyName}" />
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
        <result column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
    </resultMap>

</#if>
<#if baseColumnList>
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
<#list table.commonFields as field>
        ${field.name},
</#list>
        ${table.fieldNames}
    </sql>

</#if>
</mapper>

service 层

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};

/**
 * @Description:${table.comment!} 服务类
 */
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

}
</#if>

serviceImpl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;

/**
 * @Description:${table.comment!} 服务实现类
 */
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

}
</#if>

最后效果以entity为例

package com.heima.model.user.pojos;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldNameConstants;

/**
 * @Description:APP用户信息表
 */
@Data
@NoArgsConstructor
@FieldNameConstants
@EqualsAndHashCode(callSuper = false)
@TableName("ap_user")
@ApiModel(value="ApUser对象", description="APP用户信息表")
public class ApUser implements Serializable {

    private static final long serialVersionUID = 1L;


    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "密码、通信等加密盐")
    @TableField("salt")
    private String salt;

    @ApiModelProperty(value = "用户名")
    @TableField("name")
    private String name;

    @ApiModelProperty(value = "密码,md5加密")
    @TableField("password")
    private String password;

    @ApiModelProperty(value = "手机号")
    @TableField("phone")
    private String phone;

    @ApiModelProperty(value = "头像")
    @TableField("image")
    private String image;

    @ApiModelProperty(value = "0 男 1 女 2 未知")
    @TableField("sex")
    private Boolean sex;

    @ApiModelProperty(value = "0 未 1 是")
    @TableField("is_certification")
    private Boolean isCertification;

    @ApiModelProperty(value = "是否身份认证  0否   1是")
    @TableField("is_identity_authentication")
    private Boolean isIdentityAuthentication;

    @ApiModelProperty(value = "0正常 1锁定")
    @TableField("status")
    private Boolean status;

    @ApiModelProperty(value = "0 普通用户 1 自媒体人 2 大V")
    @TableField("flag")
    private Boolean flag;

    @ApiModelProperty(value = "注册时间")
    @TableField("created_time")
    private Date createdTime;


}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1)代码生成主要依赖于freeMark模板,不同的项目需求可以通过修改freeMark模板来实现。 2)如果是后台管理系统,则可以生成管理系统基本的网站页面及其功能。其他系统则很难生成前端页面,主要困难在于模板不统一,如果页面风格都相似,也可以用模板生成页面,然后再对页面进行修改。 3)项目基本功能:根据数据库表生成基本功能代码,包含Mybatis文件,dao、servic、entity、controller以及查询页面、增加编辑页面。 4)生成过程中可以选择编辑页面所需要的字段,列表页面所需要的字段以及查询条件所需要的字段。 # 数据库 1)数据库文件在项目根目录下的doc文件夹下xcode.sql文件 2)创建数据库xCode 默认设置root账户、密码root123 3)执行xcode.sql文件的SQL,创建数据表结构即可 # 项目结构 1)项目根目录下的doc文件夹放置的是开发相关的文档 2) pom.xml 文件是maven相关配置文件 3)src.main 包下有三个文件夹,Java文件夹很明显,是Java文件相关。 resources文件夹是 配置相关的文件夹,包括spring相关配置,Mybatis相关配置,数据库相关配置,redis相关配 置都在此文件夹下,webapp文件夹下是页面相关的 4)com.cn.cooxin包,admin包主要是管理代码生成后台功能的文件,包含用户的管理、角色菜单管理,代码生成管理等,code包主要是代码生成相关的功能,common包是公共服务相关的功能,ueditor是百度编辑器相关的功能,如果不用,可以不用管。util包是开发工具类相关的功能。
Freemarker 本身并不支持生成图片,它是一个模板引擎,用于生成文本文件。但是,你可以使用 Java 的图形库(如 AWT 或 JavaFX)来生成图片,然后将图片插入到模板中。 以下是一个简单的示例,使用 AWT 绘制一张图片并将其插入到 Freemarker 模板中: Java 代码: ```java import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageGenerator { public static void generateImage(String text, String outputFileName) throws IOException { // 创建 BufferedImage 对象 BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); // 获取 Graphics2D 对象 Graphics2D g2d = image.createGraphics(); // 设置画布背景色为白色 g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, 200, 100); // 设置字体和颜色 g2d.setColor(Color.BLACK); g2d.drawString(text, 50, 50); // 保存图片 ImageIO.write(image, "png", new File(outputFileName)); } } ``` Freemarker 模板: ```html <html> <body> <h1>欢迎使用 Freemarker</h1> <img src="${imagePath}" /> </body> </html> ``` Java 代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) throws IOException { // 生成图片 ImageGenerator.generateImage("Hello, Freemarker!", "image.png"); // 创建 Freemarker 配置对象 Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); cfg.setDirectoryForTemplateLoading(new File("templates")); // 加载模板文件 Template template = cfg.getTemplate("index.ftl"); // 设置模板变量 Map<String, Object> data = new HashMap<>(); data.put("imagePath", "image.png"); // 渲染模板 StringWriter out = new StringWriter(); template.process(data, out); // 输出渲染结果 System.out.println(out.toString()); } } ``` 在这个示例中,我们创建了一个名为 `ImageGenerator` 的类,其中包含一个名为 `generateImage` 的静态方法,该方法接受要绘制的文本和输出文件名作为参数。该方法使用 AWT 创建一个 `BufferedImage` 对象,并在图像上绘制文本。最后,它将图像保存为 PNG 文件。 在 `Main` 类中,我们使用 `ImageGenerator.generateImage` 方法生成一张图片,并将图片路径传递给 Freemarker 模板中的变量 `imagePath`。然后,我们加载模板文件并使用 `Template.process` 方法渲染模板,将变量 `imagePath` 替换为实际的图片路径。最后,我们将渲染结果输出到控制台。 请注意,这只是一个简单的示例,实际情况可能更为复杂。你需要根据自己的需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值