Freemarker查询SQL生成器

package test;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

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

/**
 * Freemarker查询SQL生成器
 */
public class Freemark implements ApplicationContextAware {

	/** logger */
	private static final Logger logger = LoggerFactory
			.getLogger(Freemark.class);

	/** Spring上下文 */
	protected ApplicationContext applicationContext;

	/** freemarker configuration */
	protected Configuration cfg;

	/** freemarker template loader */
	protected StringTemplateLoader stringTL;

	public static void main(String[] args) throws Exception {

		Freemark f1 = new Freemark();
		String sql = "select orderdate, o.orderid, o.status, o.note,o.totalcost  from omorder o where 1 = 1  "
		+ "<#if orderdate_1 ??>     and o.orderdate >= '${orderdate_1}'  </#if>  "
		+ "<#if orderdate_2 ??>     and o.orderdate < '${orderdate_2}'  </#if>   <#if orderid ??>  "
		+ "   and o.orderid = '${orderid}'  </#if>  <#if note ??>     and o.note like '%${note}%' "
		+ " </#if>    <#if orderstatus ??>     and o.status = '${orderstatus}'  </#if>";
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("orderdate_1", "2012-01-01");
		root.put("msg", "您已经完成了第一个FreeMarker的示例");
		System.out.println(sql);
		System.out.println(f1.getQueryString("12", sql, root));

	}

	public String getQueryString(String queryName, String queryTemplate,
			Map<String, ?> conditions) throws IOException, TemplateException {
		if (queryTemplate == null) {
			System.out.print("查询模板不存在");
		}
		cfg = new Configuration();
		stringTL =new StringTemplateLoader();
		stringTL.putTemplate(queryName, queryTemplate);
		cfg.setTemplateLoader(stringTL);
		Template temp = cfg.getTemplate(queryName);
		StringWriter queryStringWriter = new StringWriter();
		temp.process(conditions, queryStringWriter);
		String queryString = queryStringWriter.toString();
		return queryString == null ? null : queryString.trim();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		// TODO Auto-generated method stub
		
	}

}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值