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
}
}
Freemarker查询SQL生成器
最新推荐文章于 2023-06-26 18:19:09 发布