freemarker用于生成sql语句实例
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);
}
}