---
title: "freemarker用于生成sql语句实例"
author: "prodream"
date: "2010-07-05T14:29:34Z"
tags: []
categories: ["编程语言"]
slug: "freemarker-sql"
draft: false
lastmod: "2010-07-05T14:55:53Z"
id: 705843
url: "https://prodream.iteye.com/blog/705843"
---

private static Configuration NAMEDSQL\_CONFIG = new Configuration();  
  private static StringTemplateLoader NAMEDSQL\_STL = new StringTemplateLoader();  
  static {  
    NAMEDSQL\_CONFIG.setTemplateLoader(NAMEDSQL\_STL);  
  } 

/\**  
   * 获取处理之后的命名SQL。定义命名SQL的文件名：类名.xml，命名SQL以freemarker模板方式定义。  
   * @param clz  
   * @param sqlId  
   * @param beanOrMap  
   * @return  
   \*/

 

 final public static String takeNamedSql(Class clz,String sqlId,Object beanOrMap) {  
   String clzName = clz.getCanonicalName();  
   Template tpl = null;  
   try {  
   tpl = NAMEDSQL\_CONFIG.getTemplate(sqlId);  
  } catch (IOException ex) {

 

   //不存在指定id的模板  
   InputStream is = null;  
   try {

    
       is = clz.getResourceAsStream(clz.getSimpleName() + ".xml");  
       Document doc = DocumentHelper.parseText(IOUtils.toString(is));  
       List&lt;Element&gt; es = doc.selectNodes("sqls/sql");  
       for(Element e : es)

   //以clzName-id 作为名字来保存模板

        NAMEDSQL\_STL.putTemplate(clzName + "-" + e.attributeValue("id"), e.getTextTrim());  
     }catch(Exception e) {  
       throw new IllegalStateException(e);  
     }finally {  
       IOUtils.closeQuietly(is);  
     }  
  }

  if(tpl == null) {  
   try {  
    tpl = NAMEDSQL\_CONFIG.getTemplate(clzName + "-" + sqlId);  
   } catch (IOException ex) {  
    throw new IllegalArgumentException(ex);  
   }  
  }  
  //生成sql  
  try {  
      StringWriter sw = new StringWriter();  
      Map params = asMap(beanOrMap);  
      tpl.process(params, sw);  
      return sw.toString();  
    }catch(Exception e) {  
      throw new RuntimeException(e);  
    }  
  }