mysql数据库自动生成对应的java实体类和ibatis配置文件

2 篇文章 0 订阅
1 篇文章 0 订阅

package db.tool;

import java.io.File;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class Run {

 public final static String projectPath = "E:\\w\\b\\";
 public final static String entityPackageName = "com.entities";
 public final static String configPackageName = "com.config";
 public final static String dbDriver = "com.mysql.jdbc.Driver";
 public final static String dbURL = "jdbc:mysql://127.0.0.1/businessprocess?useUnicode=true&characterEncoding=UTF-8";
 public final static String dbUser = "root";
 public final static String dbPass = "root";

 public static void main(String[] args) throws Exception {
  Run _i_run = new Run();
  File _v_folder = new File(projectPath + "src\\"
    + entityPackageName.replace(".", "\\\\"));
  if (!_v_folder.exists())
   _v_folder.mkdirs();
  _v_folder = new File(projectPath + "src\\"
    + configPackageName.replace(".", "\\\\"));
  if (!_v_folder.exists())
   _v_folder.mkdirs();
  List<String> _v_tableNameList = _i_run._m_getDbTableNameList();
  File _v_sqlMapFile = new File(projectPath + "src\\\\autoSqlMap.xml");
  if (!_v_sqlMapFile.exists())
   _v_sqlMapFile.createNewFile();
  PrintWriter _v_fw = new PrintWriter(_v_sqlMapFile, "UTF-8");
  _v_fw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
    + "<!DOCTYPE sqlMapConfig PUBLIC"
    + " \"-//ibatis.apache.org//DTD SQL Map Config 2.0//EN\""
    + " \"http://ibatis.apache.org/dtd/sql-map-config-2.dtd\">"
    + "\r\n\r\n<sqlMapConfig>\r\n\r\n\t<settings cacheModelsEnabled=\"true\" />");
  for (String _v_tblName : _v_tableNameList) {
   _v_fw.println("\t<sqlMap resource=\""
     + configPackageName.replace(".", "/") + "/"
     + _v_tblName.toLowerCase() + ".xml\" />");
   _v_tblName = _i_run._m_firstToUpperCase(_v_tblName);
   System.out.println("table name:" + _v_tblName);
   _i_run._m_packEntityAndConfig(_v_tblName);
  }
  _v_fw.println("\r\n</sqlMapConfig>");
  _v_fw.flush();
  _v_fw.close();
 }

 /**
  * 打包实体类和配置文件
  *
  * @param _v_tblName
  *            数据表名称
  * @throws Exception
  *             exception
  */
 protected void _m_packEntityAndConfig(String _v_tblName) throws Exception {
  Fields[] _v_fields = _m_getFields(_v_tblName);
  String _v_xmlName = _v_tblName.toLowerCase();
  String _v_fullClsName = entityPackageName + "." + _v_tblName;
  // 打包实体类 start //
  File _v_jFile = new File(projectPath + "src\\"
    + entityPackageName.replace(".", "\\\\") + "\\\\" + _v_tblName
    + ".java");
  if (!_v_jFile.exists())
   _v_jFile.createNewFile();
  PrintWriter _v_fw = new PrintWriter(_v_jFile, "UTF-8");
  _v_fw.println("package " + entityPackageName + ";\n");
  _v_fw.println("public class "
    + _v_tblName
    + " implements com.shareisvalue.framework.BasicEntity,java.io.Serializable {\n");
  _v_fw.println("\tprivate static final long serialVersionUID=1L;");
  for (Fields _v_f : _v_fields)
   _v_fw.println("\tprotected " + _v_f.getJavaType() + " "
     + _m_toAttributeString(_v_f.getName()) + " = null;");
  _v_fw.println("\n\tpublic " + _v_tblName + "() { }\n"); // 构造函数
  _v_fw.println("\tpublic String getTableName() {"); // 构造函数
  _v_fw.println("\t\treturn \"" + _v_xmlName + "\";");
  _v_fw.println("\t}\n");
  for (Fields _v_f : _v_fields) {
   String _v_jType = _v_f.getJavaType();
   String _v_sgName = _m_firstToUpperCase(_v_f.getName());
   String _v_fName = _m_toAttributeString(_v_f.getName());
   _v_fw.println("\tpublic " + _v_jType + " get" + _v_sgName + "() {");
   _v_fw.println("\t\treturn " + _v_fName + ";");
   _v_fw.println("\t}\n");
   _v_fw.println("\tpublic void set" + _v_sgName + "(" + _v_jType
     + " " + _v_fName + ") {");
   _v_fw.println("\t\t this." + _v_fName + " = " + _v_fName + ";");
   _v_fw.println("\t}\n");
  }
  _v_fw.println("}");
  _v_fw.flush();
  _v_fw.close();
  // 打包实体类 end //

  // 打包sql xml文件 start //
  _v_jFile = new File(projectPath + "src\\"
    + configPackageName.replace(".", "\\\\") + "\\\\" + _v_xmlName
    + ".xml");
  if (!_v_jFile.exists())
   _v_jFile.createNewFile();
  _v_fw = new PrintWriter(_v_jFile, "UTF-8");
  _v_fw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
    + "<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\""
    + " \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\r\n\r\n<sqlMap>\r\n");
  // === select all record ===
  String _v_content = "\t<select id=\"selectAllRecord." + _v_xmlName
    + "\" resultClass=\"" + _v_fullClsName
    + "\">\r\n\t\tSELECT * FROM " + _v_xmlName
    + " \r\n\t</select>\n";
  _v_fw.println(_v_content);
  // === select by primary key ===
  String _v_pkColName = _m_toAttributeString(_m_getPrimaryKeyColumn(_v_fields));
  if (_v_pkColName != null) {
   _v_content = "\t<select id=\"selectRecordByPKId." + _v_xmlName
     + "\" resultClass=\"" + _v_fullClsName
     + "\">\r\n\t\tSELECT * FROM " + _v_xmlName + " WHERE "
     + _v_pkColName + " = #" + _v_pkColName
     + "# \r\n\t</select>\r\n";
   _v_fw.println(_v_content);
  }
  // === insert record ===
  _v_content = "\t<insert id=\"insertRecord." + _v_xmlName
    + "\"\r\n\t\tparameterClass=\"" + _v_fullClsName + "\">\r\n"
    + "\t\tINSERT INTO " + _v_xmlName
    + " \r\n\t\t<dynamic prepend=\"(\">";
  for (Fields _v_fd : _v_fields) {
   _v_content += "\r\n\t\t\t<isNotEmpty property=\""
     + _m_toAttributeString(_v_fd.getName())
     + "\" prepend=\",\">" + _v_fd.getName() + "</isNotEmpty>";
  }
  _v_content += "\r\n\t\t\t)\r\n\t\t</dynamic> \r\n\t\tVALUES \r\n\t\t<dynamic prepend=\"(\">";
  for (Fields _v_fd : _v_fields) {
   _v_content += "\r\n\t\t\t<isNotEmpty property=\""
     + _m_toAttributeString(_v_fd.getName())
     + "\" prepend=\",\">#"
     + _m_toAttributeString(_v_fd.getName()) + "#</isNotEmpty>";
  }
  _v_content += "\r\n\t\t\t)\r\n\t\t</dynamic>\r\n";
  if (_v_pkColName != null)
   _v_content += "\t\t<selectKey resultClass=\"Integer\" keyProperty=\""
     + _v_pkColName
     + "\">\r\n\t\t\tSELECT LAST_INSERT_ID() AS ID\r\n\t\t</selectKey>\r\n";
  _v_content += "\t</insert>";
  _v_fw.println(_v_content);
  // === update record ===
  if (_v_pkColName != null) {
   _v_content = "\r\n\t<update id=\"updateRecord." + _v_xmlName
     + "\" parameterClass=\"" + _v_fullClsName + "\">\r\n"
     + "\t\tUPDATE " + _v_xmlName
     + "\r\n\t\t<dynamic prepend=\"SET\">";
   for (Fields _v_fd : _v_fields) {
    if (!_v_pkColName.equals(_v_fd.getName()))
     _v_content += "\r\n\t\t\t<isNotEmpty property=\""
       + _m_toAttributeString(_v_fd.getName())
       + "\" prepend=\",\">" + _v_fd.getName() + " = #"
       + _m_toAttributeString(_v_fd.getName())
       + "#</isNotEmpty>";
   }
   _v_content += "\r\n\t\t</dynamic>\r\n\t\t<dynamic prepend=\"WHERE\">\r\n\t\t\t<isNotEmpty property=\""
     + _v_pkColName
     + "\">"
     + _v_pkColName
     + " = #"
     + _v_pkColName
     + "#</isNotEmpty>\r\n\t\t</dynamic>\r\n\t</update>";
   _v_fw.println(_v_content);
  }
  // === delete record ===
  if (_v_pkColName != null) {
   _v_content = "\r\n\t<delete id=\"deleteRecordPKId." + _v_xmlName
     + "\" parameterClass=\"" + _v_fullClsName
     + "\">\r\n\t\tDELETE FROM " + _v_xmlName + " WHERE "
     + _v_pkColName + " = #" + _v_pkColName + "#\r\n\t</delete>";
   _v_fw.println(_v_content);
  }
  _v_fw.println("\r\n</sqlMap>");
  _v_fw.flush();
  _v_fw.close();
  // 打包sql xml文件 end //
 }

 /**
  * 获取主键
  *
  * @param fields
  *            数据库字段集合
  * @return 主键
  */
 protected String _m_getPrimaryKeyColumn(Fields[] fields) {
  String pkName = null;
  for (int i = 0; i < fields.length; i++)
   if (fields[i].isPrimaryKey()) {
    pkName = fields[i].getName();
    break;
   }
  return pkName;
 }

 /**
  * 前两位小写
  *
  * @param _p_attr
  *            字符串
  * @return 前两位小写字符串
  */
 protected String _m_toAttributeString(String _p_attr) {
  if (_p_attr == null)
   return null;
  char[] _v_charArray = _p_attr.toCharArray();
  if (_v_charArray.length > 0) {
   _v_charArray[0] = Character.toLowerCase(_v_charArray[0]);
   if (_v_charArray.length > 1)
    _v_charArray[1] = Character.toLowerCase(_v_charArray[1]);
  }
  return new String(_v_charArray);
 }

 /**
  * 首字母大写
  *
  * @param _p_String
  *            字符串
  * @return 首字母大写字符串
  */
 protected String _m_firstToUpperCase(String _p_String) {
  if (_p_String == null)
   return null;
  char[] _v_charArray = _p_String.toCharArray();
  if (_v_charArray.length > 0)
   _v_charArray[0] = Character.toUpperCase(_v_charArray[0]);
  return new String(_v_charArray);
 }

 /**
  * 获取数据库表对应的数据库字段
  *
  * @param tableName
  *            数据库表
  * @return 字段对象集合
  * @throws Exception
  *             exception
  */
 protected Fields[] _m_getFields(String tableName) throws Exception {
  Connection conn = null;
  PreparedStatement stmt = null;
  Fields[] fields = null;
  conn = _m_getConnection();
  ResultSet rs1 = conn.getMetaData()
    .getPrimaryKeys(null, null, tableName);
  String primaryKey = null;
  while (rs1.next()) {
   primaryKey = rs1.getString(4);
  }
  stmt = conn.prepareStatement("select * from " + tableName);
  ResultSet rs = stmt.executeQuery();
  ResultSetMetaData md = rs.getMetaData();
  int colCount = md.getColumnCount();
  fields = new Fields[colCount];
  for (int i = 0; i < fields.length; i++) {
   String colName = md.getColumnName(i + 1);
   String colType = md.getColumnTypeName(i + 1);
   boolean isPK = colName.equals(primaryKey);
   fields[i] = new Fields(colName, colType, isPK);
   fields[i].setAutoIncrease(md.isAutoIncrement(i + 1));
   fields[i].setJavaType(md.getColumnClassName(i + 1));
  }
  if (stmt != null)
   stmt.close();
  if (conn != null)
   conn.close();
  return fields;
 }

 /**
  * 获取数据库表名称集合
  *
  * @return 数据库表名称集合
  * @throws Exception
  *             exception
  */
 protected List<String> _m_getDbTableNameList() throws Exception {
  List<String> _v_tableNameList = new ArrayList<String>();
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  conn = _m_getConnection();
  stmt = conn.prepareStatement("show tables");
  rs = stmt.executeQuery();
  while (rs.next())
   _v_tableNameList.add(rs.getString(1));
  if (stmt != null)
   stmt.close();
  if (conn != null)
   conn.close();
  if (rs != null)
   rs.close();
  return _v_tableNameList;
 }

 protected Connection _m_getConnection() throws Exception {
  Class.forName(dbDriver);
  Connection conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
  return conn;
 }

}

class Fields {

 public String name = null;
 public String type = null;
 public boolean primaryKey = false;
 public boolean autoIncrease = false;
 public String javaType = null;

 public Fields(String name, String type, boolean primaryKey) {
  this.name = name;
  this.type = type;
  this.primaryKey = primaryKey;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public boolean isPrimaryKey() {
  return primaryKey;
 }

 public void setPrimaryKey(boolean primaryKey) {
  this.primaryKey = primaryKey;
 }

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 public boolean isAutoIncrease() {
  return autoIncrease;
 }

 public void setAutoIncrease(boolean autoIncrease) {
  this.autoIncrease = autoIncrease;
 }

 public String getJavaType() {
  return javaType;
 }

 public void setJavaType(String javaType) {
  this.javaType = javaType;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值