一.继承覆盖MetaBuilder类,创建新ViewMetaBuilder
package generator; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.jfinal.plugin.activerecord.dialect.OracleDialect; import com.jfinal.plugin.activerecord.generator.MetaBuilder; import com.jfinal.plugin.activerecord.generator.TableMeta; public class ViewMetaBuilder extends MetaBuilder{ public ViewMetaBuilder(DataSource dataSource) { super(dataSource); } protected void buildPrimaryKey(TableMeta tableMeta) throws SQLException { ResultSet rs = dbMeta.getPrimaryKeys(conn.getCatalog(), null, tableMeta.name); String primaryKey = ""; int index = 0; while (rs.next()) { if (index++ > 0) { primaryKey += ","; } primaryKey += rs.getString("COLUMN_NAME"); } /* if (StrKit.isBlank(primaryKey)) { throw new RuntimeException("primaryKey of table \"" + tableMeta.name + "\" required by active record pattern"); }*/ tableMeta.primaryKey = primaryKey; rs.close(); } protected ResultSet getTablesResultSet() throws SQLException { String schemaPattern = dialect instanceof OracleDialect ? dbMeta.getUserName() : null; return dbMeta.getTables(conn.getCatalog(), schemaPattern, null, new String[]{"TABLE", "VIEW"}); // return dbMeta.getTables(conn.getCatalog(), schemaPattern, null, new String[]{"TABLE"}); // 不支持 view 生成 } // 覆盖此方法,在JFinal3.4可以不用覆盖,JFinal3.5需要覆盖此方法 protected void removeNoPrimaryKeyTable(List<TableMeta> ret) { for (java.util.Iterator<TableMeta> it = ret.iterator(); it.hasNext();) { TableMeta tm = it.next(); if (StrKit.isBlank(tm.primaryKey)) { //it.remove();//注释这个代码,不然没有主键的表格不会生成 System.err.println("Skip table " + tm.name + " because there is no primary key"); } } } }
二.拷贝重新编辑生成_MappingKit模板文件
将生成_MappingKit文件的模板文件拷贝出来,添加判断主键为空(为视图或者为不设主键的表格),不添加主键映射;不为空就添加主键映射。
模板文件存在于Jfinal3.4的核心jar文件中,如截图:
拷贝并做修改:
package #(mappingKitPackageName); import com.jfinal.plugin.activerecord.ActiveRecordPlugin; /** * Generated by JFinal, do not modify this file. * <pre> * Example: * public void configPlugin(Plugins me) { * ActiveRecordPlugin arp = new ActiveRecordPlugin(...); * #(mappingKitClassName).mapping(arp); * me.add(arp); * } * </pre> */ public class #(mappingKitClassName) { public static void mapping(ActiveRecordPlugin arp) { #for (tableMeta : tableMetas) #if (tableMeta.primaryKey.contains(",")) // Composite Primary Key order: #(tableMeta.primaryKey) #end #if(tableMeta.primaryKey=='') ###修改这儿,添加主键为空判断 arp.addMapping("#(tableMeta.name)", #(tableMeta.modelName).class); #else arp.addMapping("#(tableMeta.name)", "#(tableMeta.primaryKey)", #(tableMeta.modelName).class); #end #end } }
三.将以上两个文件添加到GeneratorDemo类中
Generator generator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir); generator.setMetaBuilder(new ViewMetaBuilder(getDataSource())); generator.setMappingKitTemplate("/generator/mapping_kit_tempate.jf");//模板文件保存路径