package com.dwk.kit.sql; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import com.jfinal.kit.PathKit; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import java.io.IOException; import java.nio.file.*; /** * Created by dwk on 2019/6/27 * 用于自动装载sql文件 */ public class SqlAutoLoadKit { private static final Log log = LogFactory.get(); /** * @param arp */ public static void autoLoad(ActiveRecordPlugin arp) { autoLoad(arp, PathKit.getRootClassPath() + arp.getEngine().getBaseTemplatePath()); } public static void autoLoad(ActiveRecordPlugin arp, String path) { Path p = Paths.get(path); try { //自动装载 Files.walkFileTree(p, new SqlVisitor(arp)); log.info("SQL文件自动装载成功!"); } catch (IOException e) { log.error("SQL文件自动装载异常!请检查SQL路径"); throw new RuntimeException("SQL文件自动装载异常!请检查SQL路径"); } } }
package com.dwk.kit.sql; import cn.hutool.core.io.FileUtil; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; /** * @author Administrator */ public class SqlVisitor implements FileVisitor<Path> { private static final Log log = LogFactory.get(); private static final String SQL_EXT = "sql"; private ActiveRecordPlugin arp; public SqlVisitor(ActiveRecordPlugin arp) { this.arp = arp; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path sqlPath, BasicFileAttributes attrs) { if (SQL_EXT.equalsIgnoreCase(FileUtil.extName(sqlPath.toString()))) { log.info("loading {}", sqlPath.getFileName().toString()); arp.addSqlTemplate(sqlPath.getFileName().toString()); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.TERMINATE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } }
使用
//多个sql文件自动装载 SqlAutoLoadKit.autoLoad(arp);