SpringBoot整合FreeMarker模板引擎

发布时间:2024年01月09日

中文官方参考手册 http://freemarker.foofun.cn/

1.先加入FreeMarker依赖

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.23</version>
</dependency>

2.新建一个FreeMarkerUtil工具类

public class FreeMarkerUtil {

    /**
     * 解析 freemarker 模版
     * @param path 模板所在目录 根目录为 resources
     * @param filename ftl文件名称
     * @param data 为模版设置的数据
     * @return String
     * @throws IOException
     */
    public static String parseTemplate(String path, String filename,Object data) throws IOException {
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(FreeMarkerUtil.class, path);
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setWhitespaceStripping(true);
        Template template = configuration.getTemplate(filename);
        // 接收处理后的模版内容
        StringWriter stringWriter = new StringWriter();
        try{
            template.process(data,stringWriter);
            return stringWriter.toString();
        } catch (TemplateException e){
            return null;
        } finally {
            stringWriter.close();
        }
    }

}

3.在resources目录下新建一个mysql建表模板createTemplate.ftl

CREATE TABLE ${databaseName}.${tableName} (
  <#list columns as column>
    ${column.name} ${column.type}<#if column.autoIncrement> AUTO_INCREMENT</#if><#if column.notNull> NOT NULL</#if><#if column.primaryKey> PRIMARY KEY</#if><#if column.defaultVal != ""> DEFAULT '${column.defaultVal}'</#if><#if column.comment != ""> COMMENT '${column.comment}'</#if><#if (column_index < columns?size - 1)>,</#if>
  </#list>
) ENGINE=${engine} DEFAULT CHARSET=${charset};

4.新建字段属性类ColumnInfo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ColumnInfo {
    private String name;
    private String type;
    private boolean notNull;
    private boolean autoIncrement;
    private boolean primaryKey;
    private String defaultVal;
    private String comment;
}

5.根据数据构建模板

Map<String, Object> data = new HashMap<>();
String database = "******";
String tableName = "******";
data.put("databaseName", database);
data.put("tableName", tableName);
data.put("engine", "InnoDB");
data.put("charset", "utf8mb3");

List<ColumnInfo> columns = new ArrayList<>();
columns.add(new ColumnInfo("id", "int", true, true, true, "","ID"));
columns.add(new ColumnInfo("name", "text", false, false, false, "","姓名"));
columns.add(new ColumnInfo("age", "text", false, false, false, "","年龄"));

data.put("columns",columns);
String createTemplate = FreeMarkerUtil.parseTemplate("/", "createTemplate.ftl", data);
System.out.println(createTemplate);

6.结果生成

CREATE TABLE ******.****** (
    id int AUTO_INCREMENT NOT NULL PRIMARY KEY COMMENT 'ID',
    name text COMMENT '姓名',
    age text COMMENT '年龄'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

数据插入模板

INSERT INTO ${databaseName}.${table} (${(columns)?join(", ")})
VALUES
<#list values as row>
(<#list row as val><#if val?has_content && val?is_string>'${val?html}'<#elseif val?has_content && val?is_date>{d '${val?date}'}<#elseif val?has_content && val?is_time>{t '${val?time}'}<#elseif val?has_content && val?is_datetime>{ts '${val?datetime}'}<#elseif val?has_content && val?is_boolean>${val?string("TRUE", "FALSE")}<#else>null</#if><#if val_index != row?size - 1>,</#if></#list>)<#if row_index != values?size - 1>,</#if>
</#list>

数据查询模板

SELECT
<#if !(groups?? && groups?size > 0) && !(aggregates?? && aggregates?size > 0)>
    *
<#else>
    <#if (groups?? && groups?size > 0)>
        <#list groups as group>
            ${group} <#if group_has_next>,</#if>
        </#list>
    </#if>
    <#if (groups?? && groups?size > 0) && (aggregates?? && aggregates?size > 0)>,</#if>
    <#if (aggregates?? && aggregates?size > 0)>
        <#list aggregates as agg>
            ${agg}<#if agg_has_next>,</#if>
        </#list>
    </#if>
</#if>
FROM
    ${tableName}
<#if filterElements??>
WHERE
  <#list filterElements as filterElement>
   ( <#list filterElement.filters as filter>
        ${filter.columnName} ${filter.functionalOperator} ${filter.values} <#if filter_has_next>    ${filter.logicalOperator} </#if>
    </#list> ) <#if filterElement_has_next>    ${filterElement.logicalOperator} </#if>
   </#list>
</#if>
<#if isGroup && groups??>
GROUP BY
    <#list groups as group>
        ${group}<#if group_has_next>,</#if>
    </#list>
</#if>
<#if orders??>
ORDER BY
    <#list orders as order>
        ${order}<#if order_has_next>,</#if>
    </#list>
</#if>
文章来源:https://blog.csdn.net/I_Am_Your_God52/article/details/135481322
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。