设为首页 收藏本站
查看: 912|回复: 0

[经验分享] mysql数据库自动生成对应的java实体类和ibatis配置文件

[复制链接]

尚未签到

发表于 2016-10-24 01:47:59 | 显示全部楼层 |阅读模式
  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.isPrimaryKey()) {
    pkName = fields.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 = new Fields(colName, colType, isPK);
   fields.setAutoIncrease(md.isAutoIncrement(i + 1));
   fields.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;
 }
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-290260-1-1.html 上篇帖子: Mysql数据库服务器性能配置优化一 -- 硬件配置及优化,RAID优化 下篇帖子: Microsoft Access、MySQL 以及 SQL Server 所使用的数据类型和范围。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表