ITeye博客

freemarker运用实例

prodream · 2010-07-05 14:22 · 库 · 编程语言 · Markdown

import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;

public class Index {
	public static void main(String[] arg) {
		StringTemplateLoader STL = new StringTemplateLoader();
		Configuration CONFIG = new Configuration();
		CONFIG.setTemplateLoader(STL);

		InputStream is = null;
		try {
			is = Index.class.getResourceAsStream("index.xml");
			Document doc = DocumentHelper.parseText(IOUtils.toString(is));
			List<Element> es = doc.selectNodes("sqls/sql");
			for (Element e : es)
				STL.putTemplate(e.attributeValue("id"), e.getTextTrim());
		} catch (Exception e) {
			throw new IllegalStateException(e);
		} finally {
			IOUtils.closeQuietly(is);
		}
		Map cond = new HashMap<String, Object>();
		cond.put("userid", "'1'");
		cond.put("tbl_main", "t_accountTransfer");
		StringWriter sw = new StringWriter();
		try {
			//生成sql
			CONFIG.getTemplate("queryAccountTransfers").process(cond, sw);
			//打印
			System.out.println(sw);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}

 

freemarker: index.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<sqls>
	<sql id="queryAccountTransfers"><![CDATA[
		<#assign where>
			<#if date??>
	      and transferTime>=:date
	    </#if>
	    <#if date_end??>
	      and transferTime<=:date_end
	    </#if>
	    <#if money??>
	      and srcMoney>=:money
	    </#if>
	    <#if money_end??>
	      and srcMoney<=:money_end
	    </#if>
	    <#if scrAccountId??>
	      and srcAccountId=:scrAccountId
	    </#if>
	    <#if tgtAccountId??>
	      and tgtAccountId=:tgtAccountId
	    </#if>
	  </#assign>

    <#assign where=where?trim>
    select *
    from ${tbl_main}
    where isdelete=0 and userid=${userid}
    ${where}

	]]></sql>
</sqls>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。