Jfinal的Sql模板高级用法
- 配置Jfinal
@SpringBootConfiguration
public static ActiveRecordPlugin arp = null;
public static Engine engine= null;
@Bean
public ActiveRecordPlugin initActiveRecordPlugin() {
try {
Prop prop = PropKit.use("db.config");
String url = prop.get("dburl");
String username = prop.get("dbusername");
String password = prop.get("dbpassword");
DruidPlugin druidPlugin = new DruidPlugin(url, username, password);
WallFilter wallFilter = new WallFilter();
wallFilter.setDbType("mysql");
druidPlugin.addFilter(wallFilter);
druidPlugin.addFilter(new StatFilter());
druidPlugin.start();
arp = new ActiveRecordPlugin("mysql", druidPlugin);
arp.setShowSql(true);
arp.setCache(new IcacherForJfinal());
arp.setDevMode(true);
engine=arp.getEngine();
engine.setBaseTemplatePath("/sql");
arp.start();
log.info("The ActiveRecordPlugin is start!");
return arp;
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return null;
}
}
- 配置临时模板的读取
jfinal创建模板源码
public Template getTemplateByString(String content) {
return getTemplateByString(content, false);
}
public Template getTemplateByString(String content, boolean cache) {
if (!cache) {
return buildTemplateBySource(new StringSource(content, cache));
}
String cacheKey = HashKit.md5(content);
Template template = templateCache.get(cacheKey);
if (template == null) {
template = buildTemplateBySource(new StringSource(content, cache));
templateCache.put(cacheKey, template);
} else if (devMode) {
if (template.isModified()) {
template = buildTemplateBySource(new StringSource(content, cache));
templateCache.put(cacheKey, template);
}
}
return template;
}
- 在工具类中写如下三个方法完成sql模板的使用,调用方法时候继承该工具类即可
public String getSqlbyFile(String file, HashMap<String, Object> map) {
return readSql(getTmplSql(file), map);
}
private String getTmplSql(String file) {
try {
InputStream inputStream =this.getClass().getResourceAsStream("/sql/" + file + ".sql");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
StringBuffer stringBuffer=new StringBuffer();
while ((line = br.readLine()) != null) {
System.out.println(line);
stringBuffer.append(line+" ");
}
return String.valueOf(stringBuffer);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String readSql(String file, HashMap<String, Object> map) {
return ActiveRecordPluginConfig.engine.getTemplateByString(file).
renderToString(map);
}
- 使用模板查询
String sql = getSqlbyFile("test", hashMap);
Db.find(sql);