ITeye博客

freemarker用于生成sql语句实例

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

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<Element> 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);
    }
  }

评论(0)

暂无评论。

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