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
		
	}

}

좋은 웹페이지 즐겨찾기