Jfinal3.0有个动态sql的功能用起来还是挺爽的,如果sql文件比较少到没什么,如果sql文件多起来,一个一个的添加sql文件总让人感到不爽。于是自己就写了个自动加载sql文件的工具,代码写得不怎么样,勿喷。
package com.withub.base.utils;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
/**
* Created by xxx on 2017/4/7 0007.
* 用于自动映射sql文件
*/
public abstract class AutoMappingUtils {
private static Logger logger = LoggerFactory.getLogger(AutoMappingUtils.class);
private static final String SQL_EXT = "sql";
//默认路径是项目的相对路径
public static void auto(ActiveRecordPlugin arp){
auto(arp,"/");
}
public static void auto(ActiveRecordPlugin arp,String path){
logger.info("开始映射sql文件");
Path p = Paths.get(path);
boolean absolute = p.isAbsolute();
try {
if(absolute){//是否是绝对路径
arp.setBaseSqlTemplatePath(p.toString());
Files.walkFileTree(p,new SQLVisitor(p,arp));//自动映射
}else{//如果不是绝对路径,那么相对的就是项目的根路径
String webRootPath = PathKit.getRootClassPath();//获取项目跟路径
Path absoluteWebPath = Paths.get(webRootPath, path);//获取项目绝对根路径
//设置模板sql的位置
arp.setBaseSqlTemplatePath(absoluteWebPath.toString());
Files.walkFileTree(absoluteWebPath,new SQLVisitor(absoluteWebPath,arp));//自动映射
}
} catch (IOException e) {
throw new RuntimeException("SQL文件自动映射异常!请检查SQL路径");
}
}
/**
* sql文件访问器
* */
private static class SQLVisitor implements FileVisitor<Path>{
private Path path;
private ActiveRecordPlugin arp;
public SQLVisitor(Path path,ActiveRecordPlugin arp){
this.path = path;
this.arp = arp;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
File unknowFile = file.toFile();//未知文件
String extName = FileUtil.extName(unknowFile);//获取文件扩展名
boolean b = StrUtil.equalsIgnoreCase(extName, SQL_EXT);
if(b){//如果相等,说明是sql文件,那么加入sql文件映射中去
Path relativize = path.relativize(file);
logger.info("映射sql文件:"+relativize.toFile());
arp.addSqlTemplate(relativize.toString());//添加sql文件映射
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}
}只要指定存放sql文件的目录包括子目录中的.sql文件就会全部加载进去,支持绝对路径,相对路径就是相对于web的路径,希望大家指正。