您的位置:首页 > 数据库

Mybatis自动生成实体与基本SQL(PostgreSQL版本)

2018-01-26 14:25 561 查看
Mybatis自动生成实体与基本SQL(PostgreSQL版本)

主要有一个配置文件conf.properties,两个类 ConfUtil与GenericEntityUtil_V1。

conf.properties:配置连接数据库信息,生成哪些表名等配置

ConfUtil:用来读取配置文件

GenericEntityUtil_V1:main方法执行,生成好代码后自动弹出生成代码的文件夹。

bean_path=D:/code/mybatis/entity_bean
mapper_path=D:/code/mybatis/entity_mapper
xml_path=D:/code/mybatis/entity_mapper/xml
bean_package=com.xxl.job.authority.model
mapper_package=com.xxl.job.authority.dao
url=jdbc:postgresql://127.0.0.1:7488/heal
scheme=public
tables=xxl_job_authority_role:qar;xxl_job_authority_operator:qao
isIncludeFirstColumnOfInsertSql=false
driverName=org.postgresql.Driver
user=test
password=1234
ConfUtil
public class ConfUtil {
private static String PROPERTIES_NAME = "mybatis/postgresql/conf.properties";
private static Properties prop = null;

public static void main(String[] args) {
System.out.println(getProperty("xml_path"));
}

static {
try {
prop = new Properties();
InputStream in = ConfUtil.class.getResourceAsStream("/" + ConfUtil.PROPERTIES_NAME);
prop.load(in);
in.close();
} catch (IOException e) {
System.out.println(e);
} finally {
}

}

public static String getProperty(String key) {
String value = prop.getProperty(key);
return value == null ? "" : value;
}
}


GenericEntityUtil_V1
package com.paic.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericEntityUtil_V2 {
private String bean_path;
private String mapper_path;
private String xml_path;

private String bean_package;
private String mapper_package;
private String driverName;
private String user;
private String password;
private String url;
private String scheme;
private String isIncludeFirstColumnOfInsertSql;// insert 语句是否包含表的第一列

// 数据类型区分
private final String type_char = "char";
private final String type_date = "date";
private final String type_timestamp = "timestamp";
private final String type_int = "int";
private final String type_bigint = "bigint";
private final String type_text = "text";
private final String type_bit = "bit";
private final String type_decimal = "decimal";
private final String type_blob = "blob";
private final String type_boolean = "tinyint";

// 数据库相关
private String tableName = null;
private final Map<String, String> tableNameAndAlias = new HashMap<String, String>();
private String beanName = null;
private String mapperName = null;
private Connection conn = null;

private void init() throws ClassNotFoundException, SQLException {
bean_path = ConfUtil.getProperty("bean_path");
mapper_path = ConfUtil.getProperty("mapper_path");
xml_path = ConfUtil.getProperty("xml_path");
bean_package = ConfUtil.getProperty("bean_package");
mapper_package = ConfUtil.getProperty("mapper_package");
driverName = ConfUtil.getProperty("driverName");
url = ConfUtil.getProperty("url");
user = ConfUtil.getProperty("user");
password = ConfUtil.getProperty("password");
isIncludeFirstColumnOfInsertSql = ConfUtil.getProperty("isIncludeFirstColumnOfInsertSql");
scheme = ConfUtil.getProperty("scheme");
Class.forName(driverName);
conn = DriverManager.getConnection(url, user, password);
}

/**
* 获取所有的表
*
* @return
* @throws SQLException
*/
private List<String> getTables() throws SQLException {
List<String> tables = new ArrayList<String>();
PreparedStatement pstate = conn.prepareStatement("show tables");
ResultSet results = pstate.executeQuery();
while (results.next()) {
String tableName = results.getString(1);
tables.add(tableName);
}
return tables;
}

/**
* 获取所有配置的表
*
* @return
* @throws SQLException
*/
private List<String> getTablesByConf() throws SQLException {
List<String> result = new ArrayList<String>();
String tables = ConfUtil.getProperty("tables");
for (String tablenames : tables.split(";")) {
String[] name = tablenames.split(":");
result.add(name[0]);
tableNameAndAlias.put(name[0], name[1]);
}
return result;
}

private void processTable(String table) {
StringBuffer sb = new StringBuffer(table.length());
String tableNew = table.toLowerCase();
String[] tables = tableNew.split("_");
String temp = null;
for (int i = 0; i < tables.length; i++) {
temp = tables[i].trim();
sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
}
beanName = sb.toString();
mapperName = beanName + "Mapper";
}

private String processType(String type) {
if (type.indexOf(type_char) > -1) {
return "String";
} else if (type.indexOf(type_bigint) > -1) {
return "Long";
} else if (type.indexOf(type_date) > -1) {
return "Date";
} else if (type.indexOf(type_text) > -1) {
return "String";
} else if (type.indexOf(type_timestamp) > -1) {
return "Date";
} else if (type.indexOf(type_bit) > -1) {
return "Boolean";
} else if (type.indexOf(type_decimal) > -1) {
return "java.math.BigDecimal";
} else if (type.indexOf(type_blob) > -1) {
return "byte[]";
} else if (type.indexOf(type_boolean) > -1) {
return "Boolean";
} else if (type.indexOf(type_int) > -1) {
return "Integer";
}
return null;
}

private String processField(String field) {
StringBuffer sb = new StringBuffer(field.length());
String[] fields = field.split("_");
String temp = null;
sb.append(fields[0]);
for (int i = 1; i < fields.length; i++) {
temp = fields[i].trim();
sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
}
return sb.toString();
}

private String processTableColumnAlias(String alias, String field) {
return alias + "_" + processField(field);
}

/**
* 将实体类名首字母改为小写
*
* @param beanName
* @return
*/
private String processResultMapId(String beanName) {
return bean_package + "." + beanName ;
}

/**
* 构建类上面的注释
*
* @param bw
* @param text
* @return
* @throws IOException
*/
private BufferedWriter buildClassComment(BufferedWriter bw, String text) throws IOException {
bw.newLine();
bw.newLine();
bw.write("/**");
bw.newLine();
bw.write(" * ");
bw.newLine();
bw.write(" * " + text);
bw.newLine();
bw.write(" * ");
bw.newLine();
bw.write(" **/");
return bw;
}

/**
* 构建方法上面的注释
*
* @param bw
* @param text
* @return
* @throws IOException
*/
private BufferedWriter buildMethodComment(BufferedWriter bw, String text) throws IOException {
bw.newLine();
bw.write("\t/**");
bw.newLine();
bw.write("\t * ");
bw.newLine();
bw.write("\t * " + text);
bw.newLine();
bw.write("\t * ");
bw.newLine();
bw.write("\t **/");
return bw;
}

/**
* 生成实体类
*
* @param dbColumns
* @param types
* @param comments
* @throws IOException
*/
private void buildEntityBean(List<String> dbColumns, List<String> types, List<String> comments, String tableComment)
throws IOException {
List<String> modelColumns;
File folder = new File(bean_path);
if (!folder.exists()) {
folder.mkdir();
}

File beanFile = new File(bean_path, beanName + ".java");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
bw.write("package " + bean_package + ";");
bw.newLine();
bw.newLine();
bw.write("import java.io.Serializable;");
bw.newLine();
bw.write("import java.util.Date;");
bw.newLine();
bw = buildClassComment(bw, tableComment);
bw.newLine();
bw.write("@SuppressWarnings(\"serial\")");
bw.newLine();
bw.write("public class " + beanName + " implements Serializable {");
bw.newLine();
bw.newLine();
int size = dbColumns.size();
for (int i = 0; i < size; i++) {
bw.write("\t/**" + comments.get(i) + "**/");
bw.newLine();
bw.write("\tprivate " + processType(types.get(i)) + " " + processField(dbColumns.get(i)) + ";");
bw.newLine();
bw.newLine();
}
bw.newLine();
// 生成get 和 set方法
String tempField = null;
String _tempField = null;
String tempType = null;
for (int i = 0; i < size; i++) {
tempType = processType(types.get(i));
_tempField = processField(dbColumns.get(i));
tempField = _tempField.substring(0, 1).toUpperCase() + _tempField.substring(1);
bw.newLine();
bw.write("\tpublic void set" + tempField + "(" + tempType + " " + _tempField + "){");
bw.newLine();
bw.write("\t\tthis." + _tempField + " = " + _tempField + ";");
bw.newLine();
bw.write("\t}");
bw.newLine();
bw.newLine();
bw.write("\tpublic " + tempType + " get" + tempField + "(){");
bw.newLine();
bw.write("\t\treturn this." + _tempField + ";");
bw.newLine();
bw.write("\t}");
bw.newLine();
}
bw.newLine();
bw.write("}");
bw.newLine();
bw.flush();
bw.close();
}

/**
* 构建Mapper文件
*
* @throws IOException
*/
private void buildMapper() throws IOException {
File folder = new File(mapper_path);
if (!folder.exists()) {
folder.mkdirs();
}

File mapperFile = new File(mapper_path, mapperName + ".java");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
bw.write("package " + mapper_package + ";");
bw.newLine();
bw.newLine();
bw.write("import " + bean_package + "." + beanName + ";");
bw.newLine();
bw.write("import java.util.Date;");
bw.newLine();
bw.write("import org.apache.ibatis.annotations.Param;");
bw = buildClassComment(bw, mapperName + "数据库操作接口类");
bw.newLine();
bw.newLine();
bw.write("public interface " + mapperName + "{");
bw.newLine();
bw.newLine();
// ----------定义Mapper中的方法Begin----------
bw = buildMethodComment(bw, "查询(根据主键ID查询)");
bw.newLine();
bw.write("\t" + beanName + "  selectByPrimaryKey ( @Param(\"id\") Integer id );");
bw.newLine();
bw = buildMethodComment(bw, "删除(根据主键ID删除)");
bw.newLine();
bw.write("\t" + "int deleteByPrimaryKey ( @Param(\"id\") Integer id );");
bw.newLine();
bw = buildMethodComment(bw, "添加");
bw.newLine();
bw.write("\t" + "int insert( " + beanName + " record );");

bw.newLine();
bw = buildMethodComment(bw, "修改(根据主键ID修改)");
bw.newLine();
bw.write("\t" + "int updateByPrimaryKey ( @Param(\"po\") " + beanName
+ " record ,@Param(\"expectedDate\") Date expectedDate);");
bw.newLine();

// ----------定义Mapper中的方法End----------
bw.newLine();
bw.write("}");
bw.flush();
bw.close();
}

/**
* 构建实体类映射XML文件
*
* @param columns
* @param types
* @param comments
* @param columnsAlias
* @throws IOException
*/
private void buildMapperXml(List<String> columns, List<String> columnsAlias, List<String> types,
List<String> comments) throws IOException {
File folder = new File(xml_path);
if (!folder.exists()) {
folder.mkdirs();
}

File mapperXmlFile = new File(xml_path, mapperName + ".xml");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile)));
bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
bw.newLine();
bw.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" ");
bw.newLine();
bw.write("    \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
bw.newLine();
bw.write("<mapper namespace=\"" + mapper_package + "." + mapperName + "\">");
bw.newLine();
bw.newLine();

// 下面开始写SqlMapper中的方法
buildSQL(bw, columns, columnsAlias, types);

bw.write("</mapper>");
bw.flush();
bw.close();
}

private void buildSQL(BufferedWriter bw, List<String> dbColumns, List<String> columnsAlias, List<String> types)
throws IOException {
int size = dbColumns.size();
// 表的别名
String tableNameAlia = tableNameAndAlias.get(tableName);

bw.write("\t<resultMap id=\"" + beanName + "ResultMap\" type=\"" + processResultMapId(beanName) + "\">");

bw.newLine();
for (int i = 0; i < size; i++) {
if (i == 0) {
bw.write("\t\t<id property=\"" + processField(dbColumns.get(i)) + "\" column=\""
+ processTableColumnAlias(tableNameAlia, dbColumns.get(i)) + "\" />");
} else {
bw.write("\t\t<result property=\"" + processField(dbColumns.get(i)) + "\" column=\""
+ processTableColumnAlias(tableNameAlia, dbColumns.get(i)) + "\" />");
}
bw.newLine();
}
bw.write("\t</resultMap>");
bw.newLine();
bw.newLine();

// 通用结果列
bw.write("\t<!-- 通用查询结果列-->");
bw.newLine();
bw.write("\t<sql id=\"Base_Column_List\">");
bw.newLine();

bw.write("\t");
for (int i = 0; i < size; i++) {
bw.write("\t" + columnsAlias.get(i) + " " + processTableColumnAlias(tableNameAlia, dbColumns.get(i)));
if (i != size - 1) {
if ((i + 1) % 3 == 0) {
bw.newLine();
bw.write("\t\t,");
} else {
bw.write("\t,");
}
}
}

bw.newLine();
bw.write("\t</sql>");
bw.newLine();
bw.newLine();

// 查询(根据主键ID查询)
bw.write("\t<!-- 查询(根据主键ID查询) -->");
bw.newLine();
bw.write("\t<select id=\"selectByPrimaryKey\" resultMap=\"" + beanName
+ "ResultMap\" parameterType=\"java.lang." + processType(types.get(0)) + "\">");
bw.newLine();
bw.write("\t\t SELECT");
bw.newLine();
bw.write("\t\t <include refid=\"Base_Column_List\" />");
bw.newLine();
bw.write("\t\t FROM " + scheme + "." + tableName + " " + tableNameAlia);
bw.newLine();
bw.write("\t\t WHERE " + columnsAlias.get(0) + " = #{" + processField(dbColumns.get(0)) + "}");
bw.newLine();
bw.write("\t</select>");
bw.newLine();
bw.newLine();
// 查询完

// 删除(根据主键ID删除)
bw.write("\t<!--删除:根据主键ID删除-->");
bw.newLine();
bw.write("\t<delete id=\"deleteByPrimaryKey\" parameterType=\"java.lang." + processType(types.get(0)) + "\">");
bw.newLine();
bw.write("\t\t DELETE FROM " + scheme + "." + tableName + " " + tableNameAlia);
bw.newLine();
bw.write("\t\t WHERE " + columnsAlias.get(0) + " = #{" + processField(dbColumns.get(0)) + "}");
bw.newLine();
bw.write("\t</delete>");
bw.newLine();
bw.newLine();
// 删除完

// 添加insert方法
bw.write("\t<!-- 添加 -->");
bw.newLine();
bw.write("\t<insert id=\"insert\" parameterType=\"" + processResultMapId(beanName)
+ "\"  useGeneratedKeys=\"true\" keyProperty=\"id\" keyColumn=\"id\">");
bw.newLine();
bw.write("\t\t INSERT INTO " + scheme + "." + tableName);
bw.newLine();
bw.write(" \t\t(");
int k = 1, j = 1;
if ("true".equalsIgnoreCase(isIncludeFirstColumnOfInsertSql)) {
k = 0;
j = 0;
}
for (; k < size; k++) {
bw.write(dbColumns.get(k));
if (k != size - 1) {
bw.write(",");
}
}
bw.write(") ");
bw.newLine();
bw.write("\t\t VALUES ");
bw.newLine();
bw.write(" \t\t(");
for (; j < size; j++) {
bw.write("#{" + processField(dbColumns.get(j)) + "}");
if (j != size - 1) {
bw.write(",");
}
}
bw.write(") ");
bw.newLine();
bw.write("\t</insert>");
bw.newLine();
bw.newLine();
// 添加insert完

String tempField = null;

// ----- 修改(匹配有值的字段)
bw.write("\t<!-- 修 改-->");
bw.newLine();
bw.write("\t<update id=\"updateByPrimaryKey\" >");// parameterType=\"" + processResultMapId(beanName) + "\">");
bw.newLine();
bw.write("\t\t UPDATE " + scheme + "." + tableName);
bw.newLine();
bw.write("\t\t SET ");

bw.newLine();
tempField = null;
for (int i = 1; i < size; i++) {
tempField = processField(dbColumns.get(i));
bw.write("\t\t\t " + dbColumns.get(i) + " = #{po." + tempField + "}");
if (i != size - 1) {
bw.write(",");
}
bw.newLine();
}
bw.write("\t\t WHERE " + dbColumns.get(0) + " = #{po." + processField(dbColumns.get(0)) + "}");
bw.newLine();
bw.write("\t\t\t<if test=\"expectedDate !=null\">");
bw.newLine();
bw.write("\t\t\t\tAND update_time = #{expectedDate}");
bw.newLine();
bw.write("\t\t\t</if>");
bw.newLine();
bw.write("\t</update>");
bw.newLine();
bw.newLine();
}

/**
* 获取所有的数据库表注释
*
* @return
* @throws SQLException
*/
private Map<String, String> getTableComment() throws SQLException {
Map<String, String> maps = new HashMap<String, String>();
PreparedStatement pstate = conn.prepareStatement("SELECT table_name FROM information_schema.tables WHERE table_schema = '"+scheme+'\'');
ResultSet results = pstate.executeQuery();
while (results.next()) {
String tableName = results.getString("TABLE_NAME");
String comment = results.getString("TABLE_NAME");
maps.put(tableName, comment);
}
return maps;
}

public void generate() throws ClassNotFoundException, SQLException, IOException {
init();
String prefix = "select * from information_schema.columns where table_schema='"+scheme+"\' and table_name="; // TODO
List<String> columns = null;
List<String> columnsAlias = null;
List<String> types = null;
List<String> comments = null;
PreparedStatement pstate = null;
List<String> tables = getTablesByConf();
Map<String, String> tableComments = getTableComment();
for (String table : tables) {
columns = new ArrayList<String>();
columnsAlias = new ArrayList<String>();
types = new ArrayList<String>();
comments = new ArrayList<String>();
pstate = conn.prepareStatement(prefix +"'" + table +"'");
ResultSet results = pstate.executeQuery();
while (results.next()) {
String tableAlias = tableNameAndAlias.get(table);
columns.add(results.getString("column_name").toLowerCase());
columnsAlias.add(tableAlias + "." + results.getString("column_name").toLowerCase());
types.add(results.getString("data_TYPE"));
comments.add(results.getString("column_name"));
}
tableName = table;
processTable(table);
//TODO
String tableComment = tableComments.get(tableName);
buildEntityBean(columns, types, comments, tableComment);
buildMapper();
buildMapperXml(columns, columnsAlias, types, comments);
}
conn.close();
}

public static void main(String[] args) {
try {
new GenericEntityUtil_V2().generate();
// 自动打开生成文件的目录
Runtime.getRuntime().exec("cmd /c start explorer D:\\code\\mybatis");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: