1 项目简介
需要提前在数据库建好表,然后执行代码生成工具,会生成简单的Java文件,避免重复编写增删改查代码。类似的工具网上有很多,本人开发这个工具属于自娱自乐。这个专栏会记录开发的过程。
2 项目搭建
数据库使用MySQL :8.1.0
JDK使用1.8
1、新建一个普通的Java项目。GeneraJava项目是实际开发工具。GeneraJavaDemo是生成之后的模块。目录结构如下:
2、新建GeneraJava模块(普通的maven项目)。pom.xml内容如下:
<?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.sourceJava</groupId><artifactId>GeneraJava</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><mysql.version>8.0.17</mysql.version><apache.commons.version>3.4</apache.commons.version><lombok.version>1.16.18</lombok.version></properties><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${apache.commons.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.11.2</version></dependency></dependencies> </project>
3、application.properties 内容如下:
db.driver.name=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/generatejava?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT&allowMultiQueries=true db.username=数据库账号 db.password=数据库密码 #忽略表前缀 ignore.table.prefix=true #参数bean后缀 suffix.bean.param=query #文件输出路径 path.base=xxx/MyGeneraJava/GeneraJavaDemo/src/main/ #包名 package.base=com.generajava package.pojo=entity.pojo package.param=entity.query#需要忽略的属性 ignore.bean.tojson.field=companyId,status ignore.bean.tojson.expression=@JsonIgnore ignore.bean.tojson.class=import com.fasterxml.jackson.annotation.JsonIgnore;#日期格式序列化 bean.date.format.expresson=@JsonFormat(pattern="%s",timezone = "GMT+8") bean.date.format.class=import com.fasterxml.jackson.annotation.JsonFormat;#日期格式反序列化 bean.date.unformat.expresson=@DateTimeFormat(pattern = "%s") bean.date.unformat.class=import org.springframework.format.annotation.DateTimeFormat;
3 开发(基础模块)
3.1 PropertiesUtils.java 读取配置文件application.properties
package com.sourceJava.utils;import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;public class PropertiesUtils {private static Properties properties = new Properties();private static Map<String,String> PROPER_MAP = new HashMap<>();static {InputStream is = null;try {is = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");properties.load(is);Iterator<Object> it = properties.keySet().iterator();while(it.hasNext()){String key = (String) it.next();PROPER_MAP.put(key,properties.getProperty(key));}}catch (Exception e){e.printStackTrace();}finally {if(is != null){try {is.close();}catch (Exception e1){e1.printStackTrace();}}}}public static String getValue(String key){return PROPER_MAP.get(key);}public static void main(String[] args) {System.out.println(getValue("db.driver.name"));}
}
3.2 Constants.java 项目启动加载默认配置
package com.sourceJava.bean;import com.sourceJava.utils.PropertiesUtils;public class Constants {public static Boolean IGNORE_TABLE_PERFIX;public static String SUFFIX_BEAN_PARAM;public final static String[] SQL_DATE_TIME_TYPE = new String[]{"datetime","timestamp"};public final static String[] SQL_DATE_TYPE = new String[]{"date"};public final static String[] SQL_DECIMAL_TYPE = new String[]{"decimal","double","float"};public final static String[] SQL_STRING_TYPE = new String[]{"char","varchar","text","mediumtext","longtext"};public final static String[] SQL_INTEGER_TYPE = new String[]{"int","tinyint"};public final static String[] SQL_LONG_TYPE = new String[]{"bigint"};private static String PATH_JAVA = "java";private static String PATH_RESOURCE = "resource";public static String PATH_BASE;public static String PACKAGE_BASE;public static String PATH_POJO;public static String PACKAGE_POJO;//需要忽略的属性public static String IGNORE_BEAN_TOJSON_FIELD;public static String IGNORE_BEAN_TOJSON_EXPRESSION;public static String IGNORE_BEAN_TOJSON_CLASS;//日期序列化public static String BEAN_DATE_FORMAT_EXPRESSON;public static String BEAN_DATE_FORMAT_CLASS;//日期反序列化public static String BEAN_DATE_UNFORMAT_EXPRESSON;public static String BEAN_DATE_UNFORMAT_CLASS;static {IGNORE_BEAN_TOJSON_FIELD = PropertiesUtils.getValue("ignore.bean.tojson.field");IGNORE_BEAN_TOJSON_EXPRESSION = PropertiesUtils.getValue("ignore.bean.tojson.expression");IGNORE_BEAN_TOJSON_CLASS = PropertiesUtils.getValue("ignore.bean.tojson.class");//日期序列化BEAN_DATE_FORMAT_EXPRESSON = PropertiesUtils.getValue("bean.date.format.expresson");BEAN_DATE_FORMAT_CLASS = PropertiesUtils.getValue("bean.date.format.class");//日期反序列化BEAN_DATE_UNFORMAT_EXPRESSON = PropertiesUtils.getValue("bean.date.unformat.expresson");BEAN_DATE_UNFORMAT_CLASS = PropertiesUtils.getValue("bean.date.unformat.class");IGNORE_TABLE_PERFIX = Boolean.valueOf(PropertiesUtils.getValue("ignore.table.prefix"));SUFFIX_BEAN_PARAM = PropertiesUtils.getValue("suffix.bean.param");PACKAGE_BASE = PropertiesUtils.getValue("package.base");PACKAGE_POJO = PACKAGE_BASE + "." + PropertiesUtils.getValue("package.pojo");PATH_BASE = PropertiesUtils.getValue("path.base");PATH_BASE = PATH_BASE + PATH_JAVA;PATH_BASE = PATH_BASE.replace(".","/");PATH_POJO = PATH_BASE + "/" + PACKAGE_POJO.replace(".","/");}public static void main(String[] args) {System.out.println(PACKAGE_POJO);System.out.println(PATH_POJO);}
}
3.3 tb_product_info.sql 数据脚本
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for tb_product_info
-- ----------------------------
DROP TABLE IF EXISTS `tb_product_info`;
CREATE TABLE `tb_product_info` (`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',`company_id` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '公司ID',`code` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '公司编码',`product_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品名称',`price` decimal(15, 2) NULL DEFAULT NULL COMMENT '商品价格',`sku_type` tinyint NULL DEFAULT NULL COMMENT 'sku类型',`color_type` tinyint NULL DEFAULT NULL COMMENT '颜色类型',`craete_time` datetime NULL DEFAULT NULL COMMENT '创建时间',`crate_date` date NULL DEFAULT NULL COMMENT '创建日期',`stock` bigint NULL DEFAULT NULL COMMENT '库存',`status` tinyint NULL DEFAULT NULL COMMENT '状态',PRIMARY KEY (`id`) USING BTREE,UNIQUE INDEX `idx_code`(`code`) USING BTREE,INDEX `idx_sku_type`(`sku_type`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '商品信息表' ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;
3.4 TableInfo.java 定义表通用属性
public class TableInfo {private String tableName;//表名private String beanName;//bean名称private String beanParamName;//参数名称private String comment;//注释private Map<String, List<FieldInfo>> keyIndexMap = new LinkedHashMap<>();//唯一索引集合private Boolean haveDate = false;//是否有date类型private Boolean haveDateTime = false;//是否有时间类型private Boolean haveBigDecimal = false;//是否有bigdecimal类型private List<FieldInfo> fieldInfoList = new ArrayList();public List<FieldInfo> getFieldInfoList() {return fieldInfoList;}public void setFieldInfoList(List<FieldInfo> fieldInfoList) {this.fieldInfoList = fieldInfoList;}public String getTableName() {return tableName;}public void setTableName(String tableName) {this.tableName = tableName;}public String getBeanName() {return beanName;}public void setBeanName(String beanName) {this.beanName = beanName;}public String getBeanParamName() {return beanParamName;}public void setBeanParamName(String beanParamName) {this.beanParamName = beanParamName;}public String getComment() {return comment;}public void setComment(String comment) {this.comment = comment;}public Map<String, List<FieldInfo>> getKeyIndexMap() {return keyIndexMap;}public void setKeyIndexMap(Map<String, List<FieldInfo>> keyIndexMap) {this.keyIndexMap = keyIndexMap;}public Boolean getHaveDate() {return haveDate;}public void setHaveDate(Boolean haveDate) {this.haveDate = haveDate;}public Boolean getHaveDateTime() {return haveDateTime;}public void setHaveDateTime(Boolean haveDateTime) {this.haveDateTime = haveDateTime;}public Boolean getHaveBigDecimal() {return haveBigDecimal;}public void setHaveBigDecimal(Boolean haveBigDecimal) {this.haveBigDecimal = haveBigDecimal;}@Overridepublic String toString() {return "TableInfo{" +"tableName='" + tableName + '\'' +", beanName='" + beanName + '\'' +", beanParamName='" + beanParamName + '\'' +", comment='" + comment + '\'' +", keyIndexMap=" + keyIndexMap +", haveDate=" + haveDate +", haveDateTime=" + haveDateTime +", haveBigDecimal=" + haveBigDecimal +", fieldInfoList=" + fieldInfoList +'}';}
}
3.5 FieldInfo.java定义字段通用属性
public class FieldInfo {private String fieldName;//字段名称private String propertyName;//属性名称private String sqlType;// 数据库字段类型private String javaType;// Java字段类型private String comment; //数据库字段备注private Boolean isAutoIncrement;//是否自增public String getFieldName() {return fieldName;}public void setFieldName(String fieldName) {this.fieldName = fieldName;}public String getPropertyName() {return propertyName;}public void setPropertyName(String propertyName) {this.propertyName = propertyName;}public String getSqlType() {return sqlType;}public void setSqlType(String sqlType) {this.sqlType = sqlType;}public String getJavaType() {return javaType;}public void setJavaType(String javaType) {this.javaType = javaType;}public String getComment() {return comment;}public void setComment(String comment) {this.comment = comment;}public Boolean getAutoIncrement() {return isAutoIncrement;}public void setAutoIncrement(Boolean autoIncrement) {isAutoIncrement = autoIncrement;}@Overridepublic String toString() {return "FieldInfo{" +"fieldName='" + fieldName + '\'' +", propertyName='" + propertyName + '\'' +", sqlType='" + sqlType + '\'' +", javaType='" + javaType + '\'' +", comment='" + comment + '\'' +", isAutoIncrement=" + isAutoIncrement +'}';}
}
3.6 MyStringUtils.java字符串工具类
public class MyStringUtils {//第一个字母转换为大写public static String upCaseFirstLetter(String field){if(org.apache.commons.lang3.StringUtils.isEmpty(field)){return field;}return field.substring(0,1).toUpperCase() + field.substring(1);}//第一个字母转换成小写public static String lowerCaseFirstLetter(String field){if(org.apache.commons.lang3.StringUtils.isEmpty(field)){return field;}return field.substring(0,1).toLowerCase() + field.substring(1);}}
3.7 DateUtils.java 日期工具类
public class DateUtils {public static final String YYYY_MM_DD = "yyyy-MM-dd";public static final String _YYYY_MM_DD = "yyyy/MM/dd";public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";//Date 转 Stringpublic static String dateParseToString(String pattern, Date date){return new SimpleDateFormat(pattern).format(date);}//String 转 Datepublic static Date stringParseToDate(String date,String pattern) throws ParseException {return new SimpleDateFormat(pattern).parse(date);}
}