首先导入相关jar包
org.mybatis.generator mybatis-generator 1.3.6 org.mybatis.generator mybatis-generator-maven-plugin 1.3.6 mysql mysql-connector-java 8.0.12
package com.XX.dm.esbModules.Util;
import com.XX.dm.esbModules.entity.DO.SmsContractElevatorDO;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 根据数据库表结构 自动生成java Bean 自动生成增删改查 不包括列表查看
*/
public class AutoBean {
// mysql 驱动类
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
// 数据库登录用户名
private static final String USER = "admin";
// 数据库登录密码
private static final String PASSWORD = "admin";
// 数据库连接地址
private static final String URL = "jdbc:mysql://XXXXXXXXX:3306/XXXXX?serverTimezone=Asia/Shanghai&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
private static String tablename;
private String[] colnacapp; // 列名数组
private String[] colTypes; // 列名类型数组
private int[] colSizes; // 列名大小数组
private boolean f_util = false; // 是否需要导入包java.util.*
private boolean f_sql = false; // 是否需要导入包java.sql.*
private static String tablename_old;
/**
* 获取指定数据库中包含的表 TBlist
*
* @time 2016年3月4日下午5:54:52
* @packageName com.util
* @return 返回所有表名(将表名放到一个集合中)
* @throws Exception
*/
public List TBlist() throws Exception {
// 访问数据库 采用 JDBC方式
Class.forName(DRIVER);
Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
DatabaseMetaData md = con.getMetaData();
List list = null;
ResultSet rs = md.getTables(null, null, null, null);
if (rs != null) {
list = new ArrayList();
}
while (rs.next()) {
// System.out.println("|表" + (i++) + ":" + rs.getString("TABLE_NAME"));
String tableName = rs.getString("TABLE_NAME");
list.add(tableName);
}
rs = null;
md = null;
con = null;
return list;
}
/**
* 生成DO类返回类名
*
* @param TBlist
* @param packageName
* @return
* @throws Exception
*/
public String GenEntity(List TBlist, String packageName) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSetMetaData rsmd = null;
// 访问数据库 采用 JDBC方式
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
for (int k = 0; k < TBlist.size(); k++) {
tablename = TBlist.get(k);
tablename_old = TBlist.get(k);
String strsql = "select * from " + tablename;
pstmt = conn.prepareStatement(strsql);
rsmd = pstmt.getMetaData();
int size = rsmd.getColumnCount();
// 共有多少列
colnacapp = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < rsmd.getColumnCount(); i++) {
colnacapp[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if (colTypes[i].equalsIgnoreCase("datetime")) {
f_util = true;
}
if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) {
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
tablename = toHump(tablename);
markerJavaFile(initcap(tablename), parse(), packageName, "DO");
}
pstmt = null;
rsmd = null;
conn = null;
return tablename;
}
/**
* 解析处理(生成实体类主体代码)
*/
private String parse() {
StringBuffer sb = new StringBuffer();
sb.append("import java.io.Serializable;\r\n");
if (f_util) {
sb.append("import java.util.Date;\r\n").append("\r\n");
}
if (f_sql) {
sb.append("import java.sql.*;\r\n\r\n\r\n").append("\r\n");
}
sb.append("import org.springframework.format.annotation.DateTimeFormat;\r\n").append("\r\n");
sb.append("import com.baomidou.mybatisplus.annotations.TableId;\r\n");
sb.append("import com.baomidou.mybatisplus.annotations.TableName;\r\n");
sb.append("import com.fasterxml.jackson.annotation.JsonFormat;\r\n");
sb.append("import com.fasterxml.jackson.databind.annotation.JsonSerialize;\r\n");
sb.append("import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;\r\n").append("\r\n");
sb.append("@Data\r\n");
sb.append("@TableName(\"" + tablename_old + "\")\r\n");
sb.append("public class " + initcap(tablename) + "DO implements Serializable {\r\n").append("\r\n");
sb.append("\tprivate static final long serialVersionUID = 1L; \r\n").append("\r\n");
processAllAttrs(sb);
// processAllMethod(sb);不需要生成方法,只需要加载@Data注解即可
sb.append("\r\n").append("}\r\n");
return sb.toString();
}
/**
* 生成Controller
*
* @param beanName
* @param packageName
*/
public void makerController(String moduleName, String beanName, String packageName, String chineseName) {
String upperCase = initcap(beanName);
String lowwerCase = beanName;
String javaBean = upperCase + "DO";
String serviceName = lowwerCase + "Service";
StringBuffer sb = new StringBuffer();
sb.append("import org.apache.shiro.authz.annotation.RequiresPermissions;\r\n");
sb.append("import org.slf4j.Logger;\r\n");
sb.append("import org.slf4j.LoggerFactory;\r\n");
sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
sb.append("import org.springframework.web.bind.annotation.GetMapping;\r\n");
sb.append("import org.springframework.web.bind.annotation.ModelAttribute;\r\n");
sb.append("import org.springframework.web.bind.annotation.PostMapping;\r\n");
sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
sb.append("import org.springframework.web.bind.annotation.ResponseBody;\r\n");
sb.append("import org.springframework.web.bind.annotation.RestController;\r\n").append("\r\n");
sb.append("import com.xiolift.common.annotation.SysLogger;\r\n");
sb.append("import com.xiolift.common.constant.Constant;\r\n");
sb.append("import com.xiolift.dm.common.other.RtMsg;\r\n");
sb.append("import com.xiolift.common.util.StringUtil;\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".entity.DO.").append(javaBean)
.append(";\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".service.").append(upperCase)
.append("Service;\r\n");
sb.append("\r\n");
sb.append("@Slf4j\r\n");
sb.append("@RestController\r\n");
sb.append("@RequestMapping(\"/" + lowercap(lowwerCase.substring(3)) + "\")\r\n");
sb.append("public class " + upperCase + "Controller {\r\n").append("\r\n");
sb.append("\t@Autowired\r\n");
sb.append("\tprivate " + upperCase + "Service " + serviceName + ";\r\n").append("\r\n");
sb.append("\t@SysLogger(\"" + chineseName + "新增\")\r\n");
sb.append("\t@PostMapping(\"/insert\")\r\n");
sb.append("\t@ResponseBody\r\n");
sb.append("\t@ApiOperation(value = \"\", notes = \"\")\r\n");
sb.append("\tpublic RtMsg insert(@RequestBody HashMap map" +") {\r\n");
sb.append("\t\t\t\treturn RtMsg.requestOk();\r\n");
sb.append("\t}\r\n").append("\r\n");
markerJavaFile(upperCase, sb.toString(), packageName, "Controller");
}
public void makerService(String moduleName, String beanName, String packageName) {
String upperCase = initcap(beanName);
String lowwerCase = beanName;
String javaBean = upperCase + "DO";
StringBuffer sb = new StringBuffer();
sb.append("import java.util.List;\r\n");
sb.append("import java.util.Map;\r\n").append("\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".entity.DO.").append(javaBean)
.append(";\r\n").append("\r\n");
sb.append("public interface " + upperCase + "Service{\r\n").append("\r\n");
sb.append("}\r\n");
markerJavaFile(upperCase, sb.toString(), packageName, "Service");
}
public void makerServiceImpl(String moduleName, String beanName, String packageName) {
String upperCase = initcap(beanName);
String lowwerCase = beanName;
String javaBean = initcap(beanName) + "DO";
String mapperName = lowwerCase + "Mapper";
StringBuffer sb = new StringBuffer();
sb.append("import java.util.Date;\r\n");
sb.append("import java.util.List;\r\n");
sb.append("import java.util.Map;\r\n").append("\r\n");
sb.append("import org.slf4j.Logger;\r\n");
sb.append("import org.slf4j.LoggerFactory;\r\n");
sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
sb.append("import org.springframework.stereotype.Service;\r\n");
sb.append("import org.springframework.transaction.annotation.Transactional;\r\n").append("\r\n");
sb.append("import com.xiolift.common.constant.Constant;\r\n");
sb.append("import com.xiolift.common.util.ThreadVariable;\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".entity.DO.").append(javaBean)
.append(";\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".mapper.").append(upperCase)
.append("Mapper;\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".service.").append(upperCase)
.append("Service;\r\n").append("\r\n");
sb.append("@Slf4j\r\n");
sb.append("@Service\r\n");
sb.append("public class " + upperCase + "ServiceImpl implements " + upperCase + "Service {\r\n")
.append("\r\n");
sb.append("}\r\n");
markerJavaFile(upperCase, sb.toString(), packageName, "ServiceImpl");
}
public void makerMapper(String moduleName, String beanName, String packageName) {
String upperCase = initcap(beanName);
String javaBean = upperCase + "DO";
StringBuffer sb = new StringBuffer();
sb.append("import org.apache.ibatis.annotations.Mapper;\r\n").append("\r\n");
sb.append("import com.baomidou.mybatisplus.mapper.BaseMapper;\r\n");
sb.append("import com.xiolift.modules.").append(moduleName).append(".entity.DO.").append(javaBean)
.append(";\r\n").append("\r\n");
sb.append("@Mapper\r\n");
sb.append("public interface " + upperCase + "Mapper extends BaseMapper<" + javaBean + "> {\r\n")
.append("\r\n");
sb.append("\t@ApiOperation(value = \"根据id查询数据\")\r\n");
sb.append("\t"+javaBean +" get"+javaBean+"ById(@Param(\"id\") String id);");
sb.append("}\r\n");
markerJavaFile(upperCase, sb.toString(), packageName, "Mapper");
}
public void makerXml(String moduleName, String beanName, String packageName) {
String upperCase = initcap(beanName);
String javaBean = upperCase + "DO";
StringBuffer sb = new StringBuffer();
sb.append("\r\n");
sb.append("\r\n");
sb.append("\r\n");
sb.append("\r\n");
sb.append(" \r\n");
sb.append("\r\n");
sb.append(" \r\n");
markerXmlFile(upperCase, sb.toString(), packageName, "Mapper");
}
/**
* 创建java 文件 将生成的属性 get/set 方法 保存到 文件中 markerBean
*
* @time 2015年9月29日下午4:15:22
* @packageName fanshe
* @param className
* 类名称
* @param content
* 类内容 包括属性 getset 方法
*/
public void markerJavaFile(String className, String content, String packageName, String type) {
String folder = System.getProperty("user.dir") + "/src/main/java/" + packageName + "/";
File file = new File(folder);
if (!file.exists()) {
file.mkdirs();
}
String fileName = folder + className + type + ".java";
try {
File newdao = new File(fileName);
FileWriter fw = new FileWriter(newdao);
fw.write("package\t" + packageName.replace("/", ".") + ";\r\n" + "\r\n");
fw.write(content);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void markerXmlFile(String className, String content, String packageName, String type) {
String folder = System.getProperty("user.dir") + "/src/main/java/" + packageName + "/";
File file = new File(folder);
if (!file.exists()) {
file.mkdirs();
}
String fileName = folder + className + type + ".xml";
try {
File newdao = new File(fileName);
FileWriter fw = new FileWriter(newdao);
fw.write(content);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成所有的方法
*
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnacapp.length; i++) {
sb.append("\tpublic void set" + initcap(toHump(colnacapp[i])) + "(" + sqlType2JavaType(colTypes[i]) + " "
+ toHump(colnacapp[i]) + "){\r\n");
sb.append("\t\tthis." + toHump(colnacapp[i]) + " = " + toHump(colnacapp[i]) + ";\r\n");
sb.append("\t}\r\n").append("\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(toHump(colnacapp[i])) + "(){\r\n");
sb.append("\t\treturn " + toHump(colnacapp[i]) + ";\r\n");
sb.append("\t}\r\n").append("\r\n");
}
}
/**
* 解析输出属性
*
* @return
*/
private void processAllAttrs(StringBuffer sb) {
for (int i = 0; i < colnacapp.length; i++) {
if (0 == i) {
sb.append("\t@TableId\r\n");
sb.append("\t@JsonSerialize(using=ToStringSerializer.class)\r\n");
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + toHump(colnacapp[i]) + ";\r\n")
.append("\r\n");
} else {
if(sqlType2JavaType(colTypes[i]).equals("Long")) {
sb.append("\t@JsonSerialize(using=ToStringSerializer.class)\r\n");
}
if(sqlType2JavaType(colTypes[i]).equals("Date")) {
sb.append("\t@JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n");
sb.append("\t@DateTimeFormat(pattern=\"yyyy-MM-dd HH:mm:ss\")\r\n");
}
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + toHump(colnacapp[i]) + ";\r\n")
.append("\r\n");
}
}
}
/**
* 把输入字符串的首字母改成大写 tableName转JavaBeanName
*
* @param str
* @return
*/
private String initcap(String str) {
char[] cs = str.toCharArray();
cs[0] -= 32;
return String.valueOf(cs);
}
/**
* 把输入字符串的首字母改成小写 tableName转JavaBeanName
*
* @param str
* @return
*/
private String lowercap(String str) {
if (Character.isLowerCase(str.charAt(0))) {
return str;
}else {
return (new StringBuilder()).append(Character.toLowerCase(str.charAt(0))).append(str.substring(1))
.toString();
}
}
private String sqlType2JavaType(String sqlType) {
if (sqlType.equalsIgnoreCase("bit")) {
return "Integer";
} else if (sqlType.equalsIgnoreCase("tinyint")) {
return "Integer";
} else if (sqlType.equalsIgnoreCase("smallint")) {
return "short";
} else if (sqlType.equalsIgnoreCase("int")) {
return "Integer";
} else if (sqlType.equalsIgnoreCase("bigint")) {
return "Long";
} else if (sqlType.equalsIgnoreCase("float")) {
return "Float";
} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real")) {
return "Double";
} else if (sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")) {
return "Double";
} else if (sqlType.equals("DOUBLE")) {
return "Double";
} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")) {
return "String";
} else if (sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("date")) {
return "Date";
} else if (sqlType.equalsIgnoreCase("time")) {
return "Time";
}
else if (sqlType.equalsIgnoreCase("image")) {
return "Blob";
} else if (sqlType.equalsIgnoreCase("text")) {
return "Clob";
}
return null;
}
/**
* 下划线转驼峰
*/
private String toHump(String str) {
return HumpUtil.lineToHump(str);
}
public static void main(String[] args) throws Exception {
AutoBean auto = new AutoBean();
/**
* 自动生成该库所有表的java类 List list = auto.TBlist();
*/
List list = new ArrayList<>();
list.add("spc_work_part_info");
String beanName = auto.GenEntity(list, " xiolift-spc-esb-biz/src/main/java/com/xiolift/dm/esbModules/entity/DO");
auto.makerController("esbModules", beanName, "xiolift-spc-esb-biz/src/main/java/com/xiolift/dm/esbModules/controller", "");
auto.makerService("esbModules", beanName, "xiolift-spc-esb-biz/src/main/java/com/xiolift/dm/esbModules/service");
auto.makerServiceImpl("esbModules", beanName, "xiolift-spc-esb-biz/src/main/java/com/xiolift/dm/esbModules/service/Impl");
auto.makerMapper("esbModules", beanName, "xiolift-spc-esb-biz/src/main/java/com/xiolift/dm/esbModules/mapper");
auto.makerXml("esbModules", beanName, "xiolift-spc-esb-biz/src/main/resources/esbMapper");
}
}
package com.XX.dm.esbModules.Util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HumpUtil {
private static Pattern linePattern = Pattern.compile("_(\\w)");
/**下划线转驼峰*/
public static String lineToHump(String str){
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)})*/
public static String humpToLine(String str){
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/**驼峰转下划线,效率比上面高*/
public static String humpToLine2(String str){
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String lineToHump = lineToHump("f_parent_no_leader");
System.out.println(lineToHump);//fParentNoLeader
System.out.println(humpToLine(lineToHump));//f_parent_no_leader
System.out.println(humpToLine2(lineToHump));//f_parent_no_leader
}
}