Kaynağa Gözat

first commit

daqian 4 yıl önce
ebeveyn
işleme
a3b20f4080

+ 8 - 0
.gitignore

@@ -12,3 +12,11 @@
 # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
 hs_err_pid*
 
+*.iml
+**/.idea/
+/.idea/
+.idea/
+*.idea/
+.idea_modules/
+target/
+.settings/

+ 51 - 0
database/pom.xml

@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>com.jzdsh</groupId>
+  <artifactId>database</artifactId>
+  <version>1.0</version>
+
+  <name>database</name>
+
+  <description>the general database class library of jzdsh</description>
+  <url>http://www.jzdsh.com/</url>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    <maven.compiler.source>1.8</maven.compiler.source>
+    <maven.compiler.target>1.8</maven.compiler.target>
+  </properties>
+
+  <dependencies>
+
+    <dependency>
+      <groupId>com.jfinal</groupId>
+      <artifactId>jfinal</artifactId>
+      <version>4.8</version>
+    </dependency>
+
+    <dependency>
+      <groupId>com.jzdsh</groupId>
+      <artifactId>utils</artifactId>
+      <version>1.0</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+
+  </build>
+
+  <distributionManagement>
+    <repository>
+      <id>rdc-releases</id>
+      <url>https://repo.rdc.aliyun.com/repository/124979-release-U0ysiy/</url>
+    </repository>
+    <snapshotRepository>
+      <id>rdc-snapshots</id>
+      <url>https://repo.rdc.aliyun.com/repository/124979-snapshot-42WeYF/</url>
+    </snapshotRepository>
+  </distributionManagement>
+</project>

+ 13 - 0
database/src/main/java/com/jzdsh/App.java

@@ -0,0 +1,13 @@
+package com.jzdsh;
+
+/**
+ * Hello world!
+ *
+ */
+public class App 
+{
+    public static void main( String[] args )
+    {
+        System.out.println( "Hello World!" );
+    }
+}

+ 87 - 0
database/src/main/java/com/jzdsh/common/database/DbConfig.java

@@ -0,0 +1,87 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.kit.PropKit;
+import com.jfinal.plugin.druid.DruidPlugin;
+
+/**
+ * 这是数据的配置,支持多数据库,多数据源
+ *
+ * @author daqian.ji
+ */
+public class DbConfig {
+
+    /**
+     * 配置名称,如果配置名称留空,表示是默认的数据库
+     */
+    private String configName;
+
+    /**
+     * JDBC链接
+     */
+    private String jdbcUrl;
+
+    /**
+     * 用户名称
+     */
+    private String userName;
+
+    /**
+     * 密码
+     */
+    private String password;
+
+    //region property
+    public String getConfigName() {
+        return configName;
+    }
+
+    public void setConfigName(String configName) {
+        this.configName = configName;
+    }
+
+    public String getJdbcUrl() {
+        return jdbcUrl;
+    }
+
+    public void setJdbcUrl(String jdbcUrl) {
+        this.jdbcUrl = jdbcUrl;
+    }
+
+    public String getUserName() {
+        return userName;
+    }
+
+    public void setUserName(String userName) {
+        this.userName = userName;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+    //endregion
+
+    static DbConfig config = null;
+    public static DbConfig getNormal(){
+        if(null == config) {
+            new DbConfig("normal", PropKit.get("db.url"), PropKit.get("db.username"), PropKit.get("db.password"));
+        }
+        return config;
+    }
+
+
+    public DbConfig(String configName,String jdbcUrl,String userName,String password){
+        this.configName = configName;
+        this.jdbcUrl = jdbcUrl;
+        this.userName = userName;
+        this.password = password;
+    }
+
+    public static DruidPlugin getDruidPlugin(DbConfig config) {
+        DruidPlugin druidPlugin = new DruidPlugin(config.getJdbcUrl(), config.getUserName(), config.getPassword());
+        return druidPlugin;
+    }
+}

+ 20 - 0
database/src/main/java/com/jzdsh/common/database/DbEnum.java.bak

@@ -0,0 +1,20 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.kit.PropKit;
+
+public enum DbEnum {
+    normal(new DbConfig("normal", PropKit.get("db.url"), PropKit.get("db.username"), PropKit.get("db.password")));
+
+    public DbConfig getConfig() {
+        return config;
+    }
+
+    /**
+     * 配置名称,如果配置名称留空,表示是默认的数据库
+     */
+    private DbConfig config;
+
+    private DbEnum(DbConfig config) {
+        this.config = config;
+    }
+}

+ 109 - 0
database/src/main/java/com/jzdsh/common/database/JFMysqlDialect.java

@@ -0,0 +1,109 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.plugin.activerecord.Record;
+import com.jfinal.plugin.activerecord.Table;
+import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 重写增加和保存的
+ */
+public class JFMysqlDialect extends MysqlDialect {
+
+    /**
+     * Do not delete the String[] pKeys parameter, the element of pKeys needs to trim()
+     */
+    @Override
+    public void forDbSave(String tableName, String[] pKeys, Record record, StringBuilder sql, List<Object> paras) {
+        tableName = tableName.trim();
+        trimPrimaryKeys(pKeys);	// important
+
+        sql.append("insert into ");
+        sql.append(tableName).append("(");
+        StringBuilder temp = new StringBuilder();
+        temp.append(") values(");
+
+        for (Map.Entry<String, Object> e: record.getColumns().entrySet()) {
+            if (paras.size() > 0) {
+                sql.append(", ");
+                temp.append(", ");
+            }
+            sql.append("`").append(e.getKey()).append("`");
+            temp.append("?");
+            paras.add(e.getValue());
+        }
+        sql.append(temp.toString()).append(")");
+    }
+
+    @Override
+    public void forDbUpdate(String tableName, String[] pKeys, Object[] ids, Record record, StringBuilder sql, List<Object> paras) {
+        tableName = tableName.trim();
+        trimPrimaryKeys(pKeys);
+
+        sql.append("update ").append(tableName).append(" set ");
+        for (Map.Entry<String, Object> e: record.getColumns().entrySet()) {
+            String colName = e.getKey();
+            if (!isPrimaryKey(colName, pKeys)) {
+                if (paras.size() > 0) {
+                    sql.append(", ");
+                }
+                sql.append("`").append(colName).append("` = ? ");
+                paras.add(e.getValue());
+            }
+        }
+        sql.append(" where ");
+        for (int i=0; i<pKeys.length; i++) {
+            if (i > 0) {
+                sql.append(" and ");
+            }
+            sql.append("`").append(pKeys[i]).append("` = ?");
+            paras.add(ids[i]);
+        }
+    }
+
+    @Override
+    public void forModelSave(Table table, Map<String, Object> attrs, StringBuilder sql, List<Object> paras) {
+        sql.append("insert into ").append(table.getName()).append("(");
+        StringBuilder temp = new StringBuilder(") values(");
+        for (Map.Entry<String, Object> e: attrs.entrySet()) {
+            String colName = e.getKey();
+            if (table.hasColumnLabel(colName)) {
+                if (paras.size() > 0) {
+                    sql.append(", ");
+                    temp.append(", ");
+                }
+                sql.append("`").append(colName).append("`");
+                temp.append("?");
+                paras.add(e.getValue());
+            }
+        }
+        sql.append(temp.toString()).append(")");
+    }
+
+    @Override
+    public void forModelUpdate(Table table, Map<String, Object> attrs, Set<String> modifyFlag, StringBuilder sql, List<Object> paras) {
+        sql.append("update ").append(table.getName()).append(" set ");
+        String[] pKeys = table.getPrimaryKey();
+        for (Map.Entry<String, Object> e : attrs.entrySet()) {
+            String colName = e.getKey();
+            if (modifyFlag.contains(colName) && !isPrimaryKey(colName, pKeys) && table.hasColumnLabel(colName)) {
+                if (paras.size() > 0) {
+                    sql.append(", ");
+                }
+                sql.append("`").append(colName).append("` = ? ");
+                paras.add(e.getValue());
+            }
+        }
+        sql.append(" where ");
+        for (int i=0; i<pKeys.length; i++) {
+            if (i > 0) {
+                sql.append(" and ");
+            }
+            sql.append("`").append(pKeys[i]).append("` = ?");
+            paras.add(attrs.get(pKeys[i]));
+        }
+    }
+}

+ 51 - 0
database/src/main/java/com/jzdsh/common/database/_BaseModelGenerator.java

@@ -0,0 +1,51 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.kit.Kv;
+import com.jfinal.plugin.activerecord.generator.BaseModelGenerator;
+import com.jfinal.plugin.activerecord.generator.TableMeta;
+
+public class _BaseModelGenerator extends BaseModelGenerator {
+	
+	public _BaseModelGenerator(String baseModelPackageName, String baseModelOutputDir) {
+		super(baseModelPackageName, baseModelOutputDir);
+	}
+
+	@Override
+	protected void genBaseModelContent(TableMeta tableMeta) {
+
+		Kv data = Kv.by("baseModelPackageName", baseModelPackageName);
+		data.set("generateChainSetter", generateChainSetter);
+		data.set("tableMeta", tableMeta);
+
+		tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data);
+
+		StringBuilder ret = new StringBuilder("implements IBean {\r\n\r\n");
+		genTableName(tableMeta,ret);
+		genSelectFrom(ret);
+
+		tableMeta.baseModelContent = tableMeta.baseModelContent.replace("implements IBean {",ret.toString());
+	}
+
+	
+	protected String tableNameTemplate =	
+	"\t/**%n"+
+	"\t * 表名%n"+
+	"\t */%n"+
+	"\tpublic static final String TableName = \"%s\";%n%n";
+	
+	private void genTableName(TableMeta tableMeta, StringBuilder ret) {
+		ret.append(String.format(tableNameTemplate, tableMeta.name));
+	}
+	
+	protected String selectFromTemplate =	
+			"\t/**%n"+
+			"\t * select fields from tablename 根据查询字段自动构建select 语句%n"+
+			"\t */%n"+
+			"\tpublic static String SelectFrom(String fields){%n"+
+			"\t\treturn String.format(\"select %%s from %%s \",fields,TableName);%n"+
+			"\t}%n%n";
+	
+			private void genSelectFrom(StringBuilder ret) {
+				ret.append(String.format(selectFromTemplate));
+			}
+}

+ 90 - 0
database/src/main/java/com/jzdsh/common/database/_Generator.java

@@ -0,0 +1,90 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.kit.PathKit;
+import com.jfinal.kit.PropKit;
+import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
+import com.jfinal.plugin.activerecord.generator.Generator;
+import com.jfinal.plugin.activerecord.generator.ModelGenerator;
+import com.jfinal.plugin.druid.DruidPlugin;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.sql.DataSource;
+
+public class _Generator {
+// region 生成MODEL
+
+    /**
+     * 生成MODEL 这里会根据不同的数据库生成MODEL类文件至不同的文件夹中
+     *
+     * @param args
+     */
+    public static void main(String[] args) {
+        PropKit.clear();
+        //PropKit.use("local_dev.properties");
+        //generate(DbConfig.DbEnum.Spider);
+        //generate(DatabaseEnum.SpiderNew);
+    }
+
+    /**
+     * 生成实体类
+     * @param dbModelPackageName db model的包名 for example :com.chinaventure.spider.model
+     */
+    public static void generate(String dbModelPackageName) {
+        generate(DbConfig.getNormal(),dbModelPackageName);
+    }
+
+    /**
+     * 生成数据库实体类
+     * @param config 那个数据库
+     * @param dbModelPackageName db model的包名 for example :com.chinaventure.spider.model
+     */
+    public static void generate(DbConfig config,String dbModelPackageName) {
+        //主要数据库包名
+        String mainPackageName = dbModelPackageName + ".base";
+        //次要要数据库包名
+        String subPackageName = dbModelPackageName+"." + config.getConfigName() + ".base";
+
+        String baseModelPackageName = StringUtils.equalsIgnoreCase(config.getConfigName(), DbConfig.getNormal().getConfigName()) ? mainPackageName : subPackageName;
+        // base model 文件保存路径
+        String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/" + baseModelPackageName.replace('.', '/');
+
+        // model 所使用的包名 (MappingKit 默认使用的包名)
+        String modelPackageName = baseModelPackageName.substring(0, baseModelPackageName.lastIndexOf('.'));
+        // model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
+        String modelOutputDir = baseModelOutputDir + "/..";
+
+        // 数据源
+        DruidPlugin dsMysql = DbConfig.getDruidPlugin(config);
+        dsMysql.start();
+        DataSource dataSource = dsMysql.getDataSource();
+
+        // 创建生成器
+        Generator generator = new Generator(dataSource,new _BaseModelGenerator(baseModelPackageName, baseModelOutputDir),new ModelGenerator(modelPackageName, baseModelPackageName, modelOutputDir));
+
+        // 配置是否生成备注
+        generator.setGenerateRemarks(true);
+
+        // 设置数据库方言
+        generator.setDialect(new MysqlDialect());
+
+        // 设置是否生成链式 setter 方法
+        generator.setGenerateChainSetter(true);
+
+        // 添加不需要生成的表名
+        generator.addExcludedTable("");
+
+        // 设置是否在 Model 中生成 dao 对象
+        generator.setGenerateDaoInModel(true);
+
+        // 设置是否生成字典文件
+        generator.setGenerateDataDictionary(true);
+
+        // 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user",移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
+        generator.setRemovedTableNamePrefixes("t_");
+
+        // 生成
+        generator.generate();
+    }
+
+    // endregion
+}

+ 18 - 0
database/src/main/java/com/jzdsh/common/database/_MappingKit.java.bak

@@ -0,0 +1,18 @@
+package com.jzdsh.common.database;
+
+import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
+
+public class _MappingKit {
+    public static void mapping(ActiveRecordPlugin arp, DbConfig.DbEnum config) {
+
+        switch (config) {
+            case Spider:
+                com.chinaventure.spider.model._MappingKit.mapping(arp);
+                break;
+            default:
+                break;
+        }
+
+
+    }
+}