在项目中有这么一个场景,因为数据库表实在太多,有上百个,不是每个表都需要model的,jfinal自带的Generator 是针对整个数据库所有用户表的,虽然可以添加例外,但是还是很麻烦的。如果在开发中,只生成自己需要的单个数据表的model ,对于团队分工进行开发的时候还是很有用的,本文参考了http://www.jfinal.com/share/242,但是这个是针对jfinal2.2的,针对jfinal3.X版本,可以才有我的方法,代码有点丑,但是功能是达到了哈
package com.yourcho.jfinal.config.generator; import com.jfinal.kit.PathKit; import com.jfinal.plugin.activerecord.dialect.OracleDialect; import com.jfinal.plugin.activerecord.generator.Generator; import com.jfinal.plugin.hikaricp.HikariCpPlugin; import com.yourcho.jfinal.config.AppConfig; import javax.sql.DataSource; /** * 针对单个数据表生成model */ public class _JFinalModuleGenerator { public static DataSource getDataSource() { HikariCpPlugin dp = AppConfig.createHikariCpPlugin(); dp.start(); return dp.getDataSource(); } public static void main(String[] args) { // base model 所使用的包名 String baseModelPackageName = "com.yourcho.jfinal.model.base"; // base model 文件保存路径 String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/jfinal/com/yourcho/jfinal/model/base"; // model 所使用的包名 (MappingKit 默认使用的包名) String modelPackageName = "com.yourcho.jfinal.model"; // model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径) String modelOutputDir = baseModelOutputDir + "/.."; // 创建生成器 Generator gernerator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir); // 添加不需要生成的表名 gernerator.addExcludedTable("adv"); //设置方言 gernerator.setDialect(new OracleDialect()); gernerator.setMetaBuilder(new ModelBulid(getDataSource(),"PF_SYS_BRCH_AREA","3")); gernerator.setMappingKitGenerator(new MappingKitBulid(modelPackageName,modelOutputDir)); // 设置是否在 Model 中生成 dao 对象 gernerator.setGenerateDaoInModel(true); // 设置是否生成字典文件 gernerator.setGenerateDataDictionary(true); // 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user",移除前缀 "osc_"后生成的model名为 "User"而非 OscUser gernerator.setRemovedTableNamePrefixes("F_"); // 生成 gernerator.generate(); } }
MappingKitGenerator
package com.yourcho.jfinal.config.generator; import com.jfinal.plugin.activerecord.generator.MappingKitGenerator; import com.jfinal.plugin.activerecord.generator.TableMeta; import com.xiaoleilu.hutool.io.FileUtil; import com.xiaoleilu.hutool.util.CharsetUtil; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class MappingKitBulid extends MappingKitGenerator { public MappingKitBulid(String mappingKitPackageName, String mappingKitOutputDir) { super(mappingKitPackageName, mappingKitOutputDir); } @Override public void generate(List<TableMeta> tableMetas) { //获取以前的 _MappingKit 文件 String oldMappingKit = this.mappingKitOutputDir + File.separator + this.mappingKitClassName + ".java"; File oldMappingKitFile = new File(oldMappingKit); if (!oldMappingKitFile.exists()) { super.generate(tableMetas); } else { List<String> lines = FileUtil.readLines(oldMappingKitFile, CharsetUtil.CHARSET_UTF_8); List<String> newMappingKitList = new ArrayList<>(); newMappingKitList.add("package " +this.mappingKitPackageName + ";") ; String topLines = "" + "\n" + "import com.jfinal.plugin.activerecord.ActiveRecordPlugin;\n" + "\n" + "/**\n" + " * Generated by JFinal, do not modify this file.\n" + " * <pre> * \t \n" + " * * public void configPlugin(Plugins me) {\n" + " * ActiveRecordPlugin arp = new ActiveRecordPlugin(...);\n" + " * _MappingKit.mapping(arp);\n" + " * me.add(arp);\n" + " * }\n" + " * </pre>\n" + " */\n" + " \n" + " public class _MappingKit {\n" + "\n" + "\tpublic static void mapping(ActiveRecordPlugin arp) {"; newMappingKitList.add(topLines); for (int i = 0; i < tableMetas.size(); i++) { String primaryKey = tableMetas.get(i).primaryKey; String modelName = tableMetas.get(i).modelName; String name = tableMetas.get(i).name; for (Iterator it = lines.iterator(); it.hasNext(); ) { //去除arp.addMapping以外的所有行 String str = (String) it.next(); if (!str.contains(".class") &&!str.contains("Composite Primary Key")) { it.remove(); } if (str.contains(primaryKey) && str.contains(modelName)) { it.remove(); } } StringBuilder sb = new StringBuilder("\t\tarp.addMapping(\""); if(primaryKey.contains(",")){ lines.add("\t\t//Composite Primary Key order:\t"+primaryKey); } sb.append(name) .append("\", ") .append("\"").append(primaryKey).append("\", ") .append(modelName).append(".class);") ; lines.add(sb.toString()); } newMappingKitList.addAll(lines); newMappingKitList.add("\t}"); newMappingKitList.add("}"); String ret = ""; for (String s : newMappingKitList) { ret += s + "\n"; } super.writeToFile(ret); //我用的hutool的工具包,直接用的下面一行代码生成的_MappingKit.java文件 // FileUtil.writeLines(newMappingKitList,oldMappingKit, CharsetUtil.CHARSET_UTF_8,false); } } }
MetaBuilder
package com.yourcho.jfinal.config.generator; import com.jfinal.plugin.activerecord.dialect.MysqlDialect; import com.jfinal.plugin.activerecord.dialect.OracleDialect; import com.jfinal.plugin.activerecord.dialect.SqlServerDialect; import com.jfinal.plugin.activerecord.generator.MetaBuilder; import javax.sql.DataSource; public class ModelBulid extends MetaBuilder { private String createTableName; public String getCreateTableName() { return createTableName; } public void setCreateTableName(String createTableName) { this.createTableName = createTableName; } public ModelBulid(DataSource dataSource) { super(dataSource); // TODO Auto-generated constructor stub } public ModelBulid(DataSource dataSource,String createTableName,String dataType) { super(dataSource); if(dataType.equals("1")){ setDialect(new SqlServerDialect()); }else if(dataType.equals("2")){ setDialect(new MysqlDialect()); }else if(dataType.equals("3")){ setDialect(new OracleDialect()); } setCreateTableName(createTableName); // TODO Auto-generated constructor stub } @Override protected boolean isSkipTable(String tableName) { if(!tableName.equals(createTableName)){ return true; } return false; } }
//原MetaBuilder会生成所有的表,修改为指定的表(ResMetaBuilder自己的类)
gernerator.setMetaBuilder(new ResMetaBuilder(getDataSource()));
//----------------
public class ResMetaBuilder extends MetaBuilder {
public ResMetaBuilder(DataSource ds) {
super(ds);
}
@Override
protected ResultSet getTablesResultSet() throws SQLException {
String sql = "select table_name,'' REMARKS from user_tables where table_name in('table1','table2')";
PreparedStatement ps = conn.prepareStatement(sql);
return ps.executeQuery();
}
}