【jfinal】扩展JFIANL 支持加载jar包中SQL模板

原创
2017/05/26 21:03
阅读数 798

扩展 ActiveRecordPlugin 支持加载jar包中SQL模板

jfinal3.1 中新增了IStringSource ,这个接口方便大家扩展SQL模块的加载方式, 下面我说的场景是把sql模板打在jar包中进行扫描的情况。多模块项目请参考 http://git.oschina.net/log4j/LMS

/**
 * Created by jie on 2017/4/21.
 * 扫描jar中的sql文件
 */
public class ScanJarStringSource implements IStringSource {
    private String fileName;
    private String encoding;

    public ScanJarStringSource(String fileName) {
        this.fileName = fileName;
        this.encoding = ConBizConstant.CHARSET_NAME_UTF_8;
    }

    public ScanJarStringSource(String fileName, String encoding) {
        this.fileName = fileName;
        this.encoding = encoding;
    }

    public boolean isModified() {
        return true;
    }

    public String getKey() {
        return this.fileName;
    }

    public StringBuilder getContent() {
        return loadFile(fileName, encoding);
    }

    public String getEncoding() {
        return this.encoding;
    }

    private String buildFinalFileName(String fileName) {
        char firstChar = fileName.charAt(0);
        String finalFileName;
        if (firstChar != 47 && firstChar != 92) {
            finalFileName = File.separator + fileName;
        } else {
            finalFileName = fileName;
        }

        return finalFileName;
    }

    private static StringBuilder loadFile(String fileName, String encoding) {
        StringBuilder out = new StringBuilder();
        InputStream inputStream = com.jfinal.template.FileStringSource.class.getClassLoader().getResourceAsStream(fileName);
        byte[] b = new byte[4096];
        try {
            for (int n; (n = inputStream.read(b)) != -1; ) {
                out.append(new String(b, 0, n, encoding));
            }
        } catch (IOException e) {
            throw new RuntimeException("Error loading sql file.", e);
        } finally {
            if (inputStream != null) try {
                inputStream.close();
            } catch (IOException e) {
                com.jfinal.kit.LogKit.error(e.getMessage(), e);
            }
        }
        return out;
    }
}


扩展我们使用扩展的ScanJarStringSource 进行配置


public class _MappingKit {
    /**
     * 不用z
     * @param arp
     */
    public static void mapping(ActiveRecordPlugin arp) {
        arp.addSqlTemplate(new ScanJarStringSource("XXX.sql"));
    }
}

OK!

展开阅读全文
加载中

作者的其它热门文章

打赏
0
2 收藏
分享
打赏
2 评论
2 收藏
0
分享
返回顶部
顶部