如题,做了一个小插件。原因了,是因为西安疫情防控,我被居家了,在家也得干活不是。。。但是家里这个二路网是真不咋滴。。。然后客服电信让升级或换机,客服说让我本人去营业厅办理。。。我说小区铁门被焊死了。。。她说那不行必须得线下办理。。。话完,还问我要好评。。。算了,,不吐槽了,还得想其他办法啊。。。
在公司网快,没啥感觉。。。但是家里这个网不好的情况下,,,加载确实不得劲。。。
然后记得网上有大神分享过启动加速的功能,但是他用的是模板代码生成,我这个又是老项目,并不想让我的Model折腾,最好是无感的那种。。。
嗯,还是自己撸一个吧,贴码!
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.*;
import com.jfinal.template.Engine;
import com.jfinal.template.source.FileSource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 优先从项目中的临时缓存文件中加载对应关系,
* 没有缓存文件时,自动从数据库中加载关系,并生成临时缓存文件,供下次加载。
* 注意JSON解析工具使用了fastjson。
* @author 杜福忠
*/
public class FastTableBuilder extends TableBuilder {
private static final Log log = Log.getLog(FastTableBuilder.class);
private final String name = "FastTableBuilder.json";
public void build(List<Table> tableList, Config config) {
//从缓存中获取
if(new File(getFileName()).isFile()){
buildStrJson(tableList, config);
return;
}
//从数据库中加载对应关系
buildDb(tableList, config);
}
private String getFileName() {
return PathKit.getRootClassPath() + File.separator + name;
}
private void buildDb(List<Table> tableList, Config config) {
super.build(tableList, config);
Map<String, Map<String, String>> columnType = new HashMap<>(tableList.size());
for (Table table : tableList) {
Map<String, Class<?>> a = table.getColumnTypeMap();
Map<String, String> b = new HashMap<>(a.size());
columnType.put(table.getName(), b);
a.forEach((s, aClass) -> b.put(s, aClass.getName()));
}
String fileName = getFileName();
String strJson = JsonKit.toJson(columnType);
Engine.use().getTemplateByString(strJson, false).render(null, fileName);
log.info("文件生成:" + fileName);
}
private void buildStrJson(List<Table> tableList, Config config) {
String strJson = new FileSource(PathKit.getRootClassPath(), name).getContent().toString();
JSONObject tab = JSON.parseObject(strJson, JSONObject.class);
TableMapping tableMapping = TableMapping.me();
for (Table table : tableList) {
table.setColumnTypeMap(config.getContainerFactory().getAttrsMap());
if (table.getPrimaryKey() == null) {
CPI.setTablePrimaryKey(table, config.getDialect().getDefaultPrimaryKey());
}
JSONObject columnType = tab.getJSONObject(table.getName());
columnType.forEach((columnLabel, obj) -> {
Class<?> clazz = javaType.getType(obj.toString());
if (clazz != null) {
table.setColumnType(columnLabel, clazz);
}
});
tableMapping.putTable(table);
CPI.addModelToConfigMapping(table.getModelClass(), config);
}
}
}其中,json文件生成,代码偷懒使用了Engine的文件写入代码,追加极致的人可以改进。
OK,使用:
// 配置 ActiveRecordPlugin ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin); arp.setTableBuilder(new FastTableBuilder());
json表关系映射文件生成的位置是class生成位置,所以项目clean的时候,也会一起更新。
不想使用它时,只需要注释掉 arp.setTableBuilder 或者通过配置文件if去控制是否使用这个工具。
好了,分享到这里结束。希望大家都平平安安的渡过疫情!
福利图就不放了,点个赞呗~ 试试吧