Jfinal代码生成器加入AllBaseModel方便扩展代码分享

yshumk 发布于 2016/03/04 23:13
阅读 1K+
收藏 2

自从用了各位前辈开发的牛叉的Jfinal2.2后,Model生成器用得duang~duang~地,不过因为自己有时要搞些各Model通用的方法,所以有了要稍改代码生成AllBaseModel的必要。

中途打扰请教了@JFinal@DreamLu 两位大神,非常感谢

废话不多说,直接上代码,因为是过年前闲时仓促写的只是为了实现功能,加上刚毕业JAVA能力颇低,写得可能有点傻,大家看下思路就好

AllBaseModelGenerator.java


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.jfinal.kit.StrKit;
public class AllBaseModelGenerator {
    protected String      allbaseModelContent;
    protected String      packageTemplate     = "package %s;%n%n";
    protected String      importTemplate      = "import com.jfinal.plugin.activerecord.Model;%n%n";
    protected String      classDefineTemplate = null;
    protected String      baseModelPackageName;
    protected String      baseModelOutputDir;
    protected String      allbaseModelName;

    public AllBaseModelGenerator(String baseModelPackageName, String baseModelOutputDir,String allBaseModelName) {
        if (StrKit.isBlank(baseModelPackageName)) throw new IllegalArgumentException("baseModelPackageName can not be blank.");
        if (baseModelPackageName.contains("/") || baseModelPackageName.contains("\\")) throw new IllegalArgumentException("baseModelPackageName error : " + baseModelPackageName);
        if (StrKit.isBlank(baseModelOutputDir)) throw new IllegalArgumentException("baseModelOutputDir can not be blank.");
        this.baseModelPackageName = baseModelPackageName;
        this.baseModelOutputDir = baseModelOutputDir;
        this.allbaseModelName = allBaseModelName;
        this.classDefineTemplate = "/**\n" + " * Generated by JFinal.\n" + " */\n" + "@SuppressWarnings(\"serial\")\n" + "public abstract class " + allBaseModelName +"<M extends " + allBaseModelName + "<M>> extends Model<M>  {\n\n";
    }

    public void generate() {
        System.out.println("Generate allbaseModel ...");
        genBaseModelContent();
        try {
            wirtToFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected void genBaseModelContent() {
        StringBuilder ret = new StringBuilder();
        genPackage(ret);
        genImport(ret);
        genClassDefine(ret);
        ret.append(String.format("}%n"));
        allbaseModelContent = ret.toString();
    }

    protected void genPackage(StringBuilder ret) {
        ret.append(String.format(packageTemplate, baseModelPackageName));
    }

    protected void genImport(StringBuilder ret) {
        ret.append(String.format(importTemplate));
    }

    protected void genClassDefine(StringBuilder ret) {
        ret.append(classDefineTemplate);
    }

    /**
     * base model 覆盖写入
     */
    protected void wirtToFile() throws IOException {
        File dir = new File(baseModelOutputDir);
        if (!dir.exists()) dir.mkdirs();
        String target = baseModelOutputDir + File.separator + allbaseModelName + ".java";
        File file = new File(target);
        if (file.exists()) {
            return; // 若allBaseModel存在,不覆盖
        }
        FileWriter fw = new FileWriter(target);
        try {
            fw.write(allbaseModelContent);
        } finally {
            fw.close();
        }
    }
}



MyBaseModelGenerator.java



import com.jfinal.plugin.activerecord.generator.BaseModelGenerator;

/**
 * Base model 生成器
 */
public class MyBaseModelGenerator extends BaseModelGenerator{
    
    public MyBaseModelGenerator(String baseModelPackageName, String baseModelOutputDir,String allBaseModelName) {
        super(baseModelPackageName, baseModelOutputDir);
        this.importTemplate = 
                "import com.jfinal.plugin.activerecord.IBean;%n%n";;
        this.classDefineTemplate = 
                "/**%n" +
                        " * Generated by JFinal, do not modify this file.%n" +
                        " */%n" +
                        "@SuppressWarnings(\"serial\")%n" +
                        "public abstract class %s<M extends %s<M>> extends " + allBaseModelName + "<M> implements IBean {%n%n";
    }
    
}


MyGenerator.java

import javax.sql.DataSource;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.activerecord.generator.ModelGenerator;
public class MyGenerator extends Generator {
    protected AllBaseModelGenerator allBaseModelGenerator;

    public MyGenerator(DataSource dataSource, String baseModelPackageName, String baseModelOutputDir, String modelPackageName, String modelOutputDir, String allBaseModelName) {
        super(dataSource, new MyBaseModelGenerator(baseModelPackageName, baseModelOutputDir, allBaseModelName), new ModelGenerator(modelPackageName, baseModelPackageName, modelOutputDir));
        this.allBaseModelGenerator = new AllBaseModelGenerator(baseModelPackageName, baseModelOutputDir, allBaseModelName);
    }
    
    public void generate() {
        super.generate();
        allBaseModelGenerator.generate();
    }
}



MyGeneratorDemo.java
import javax.sql.DataSource;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.druid.DruidPlugin;
/**
 * GeneratorDemo
 */
public class MyGeneratorDemo {
    public static DataSource getDataSource() {
        Prop p = PropKit.use("settings.properties");
        DruidPlugin druid_local = new DruidPlugin(p.get("jdbc.url"), p.get("jdbc.username"), p.get("jdbc.password"));
        druid_local.start();
        return druid_local.getDataSource();
    }

    public static void main(String[] args) {
        // 注意修改成实际项目名
        String projectName = "xxx";
        // base model 所使用的包名
        String baseModelPackageName = "com.xxx." + projectName + ".model.base";
        // base model 文件保存路径
        String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/com/zhwyd/" + projectName + "/model/base";
        // model 所使用的包名 (MappingKit 默认使用的包名)
        String modelPackageName = "com.xxx." + projectName + ".model";
        // model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
        String modelOutputDir = baseModelOutputDir + "/..";
        String allBaseModelName = "AllBaseModel";
        // 创建生成器
        Generator gernerator = new MyGenerator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir,allBaseModelName);
        // // 添加不需要生成的表名
        // gernerator.addExcludedTable("adv");
        // 设置是否在 Model 中生成 dao 对象
        gernerator.setGenerateDaoInModel(true);
        // 设置是否生成字典文件
        gernerator.setGenerateDataDictionary(true);
        // 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user",移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
        // gernerator.setRemovedTableNamePrefixes("t_");
        // 生成
        gernerator.generate();
    }
}



第一次这样发帖,不知道排版会不会很乱~贴出来给需要的朋友~


加载中
0
yshumk
yshumk

生成的AllBaseModel是没方法的,可以自行发挥比如加些类似:

import java.util.List;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public abstract class AllBaseModel<M extends AllBaseModel<M>> extends Model<M>  {
    
    public String getTableName() {
        return TableMapping.me().getTable(getClass()).getName();
    }
    
    public List<M> getAll() {
        return this.find("select * from " + getTableName());
    }
    /**
     * 保存或者更新model
     * @return boolean
     */
    public boolean saveOrUpdate() {
        Table table = TableMapping.me().getTable(this.getClass());
        //获取第一个主键,2.2返回多主键数据的情况下
        Object pKey = this.get(table.getPrimaryKey()[0]);
        if (null == pKey) {
            return this.save();
        }
        return this.update();
    }
}



saveOrUpdate() 是抄卢老师 http://blog.dreamlu.net/blog/70 这篇文章的~

0
JFinal
JFinal
刚毕业就能写出这样好的代码,将来前途不可限量啊 
JFinal
JFinal
回复 @yshumk : 能学以致用,举一反三,这是走向成功的先决条件
yshumk
yshumk
波总谬赞了,基本是抄Jfinal生成器的实现
返回顶部
顶部