private static Logger logger = LoggerFactory.getLogger(SqlResourceResolver.class);
/**
* 添加sql模板
* @param arp
* @param sqlFilePath
*/
public static void addSqlTemplate(ActiveRecordPlugin arp,String sqlFilePath) {
logger.info("装载sql模板");
try {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(sqlFilePath+"/*");
if (resources!=null&&resources.length>0) {
for (Resource resource : resources) {
//只读取.sql后缀名的sql文件
if (resource.getFilename().contains(".sql")) {
if (".sql".equals(resource.getFilename().substring(resource.getFilename().length()-4, resource.getFilename().length()))) {
String content = getContent(resource.getFile());
if (StrUtil.isNotBlank(content)) {
arp.addSqlTemplate(new StringSource(content, true));
logger.info("添加[{}]到ActiveRecordPlugin",resource.getFilename());
}
}
}
}
}
} catch (Exception e) {
logger.error("装载sql模板时出错",e);
e.printStackTrace();
}
}
/**
*
* @Title: getContent
* @Description: 根据文件读取内容
* @param: @param file
* @param: @return 参数说明
* @return: String 返回类型
* @throws
*/
private static String getContent(File file){
try {
FileReader fileReader = new FileReader(file,"UTF-8");
return fileReader.readString();
} catch (Exception e) {
e.printStackTrace();
logger.error("读取文件内容时出错",e);
return null;
}
}使用方法
public ActiveRecordPlugin activeRecordPlugin() {
logger.info("设置ActiveRecord");
ActiveRecordPlugin arp = new ActiveRecordPlugin(transactionAwareDataSourceProxy());
arp.setDialect(new MysqlDialect());
arp.setShowSql(true);
//多个sql文件自动装载
SqlResourceResolver.addSqlTemplate(arp, "sql");
//sql文件映射器
_MappingKit.mapping(arp);
arp.start();
return arp;
}项目地址:demo
亲测打包后可用