13693261870
2022-10-20 93b9a4bd47bfec774894928392d52a61fca07c38
JavaCode/FrmMain.cs
@@ -1,14 +1,10 @@
using JavaCode.cs;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
@@ -16,689 +12,23 @@
{
    public partial class FrmMain : Form
    {
        #region 成员变量+构造函数
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;
        private PostgreHelper _dbHelper;
        private List<TabInfo> _list;
        public FrmMain()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        private void btnSys_Click(object sender, EventArgs e)
        {
            _dbHelper = new PostgreHelper(DbEnum.langfang);
        }
        #endregion
        #region 查询表结构
        private void btnReadTab_Click(object sender, EventArgs e)
        {
            string txtTab = this.txtTabPre.Text.Trim();
            string sql = "select c.relname as \"tab\", cast(obj_description(c.oid) as varchar) as \"desc\", a.attnum as \"num\", a.attname as \"col\", concat_ws('', t.typname, SUBSTRING(format_type(a.atttypid, a.atttypmod) from '\\(.*\\)')) as \"type\", d.description as \"bak\" from pg_attribute a left join pg_description d on d.objoid = a.attrelid and d.objsubid = a.attnum left join pg_class c on a.attrelid = c.oid left join pg_type t on a.atttypid = t.oid where a.attnum >= 0 and c.relname like '" + txtTab + "%' and obj_description(c.oid) is not null and relnamespace=" + this.txtNS.Text.Trim() + " order by c.relname desc, a.attnum asc";
            DataTable dt = _dbHelper.GetDataTable(sql, null);
            _list = ModelHandler.FillModel<TabInfo>(dt);
            if (_list == null || _list.Count == 0)
            {
                MessageBox.Show("没有查询到数据!");
                return;
            }
            List<string> tabList = new List<string>();
            foreach (TabInfo ti in _list)
            {
                if (!tabList.Contains(ti.tab))
                {
                    tabList.Add(ti.tab);
                }
            }
            this.tabList.DataSource = tabList;
            FrmSys frmSys = new FrmSys();
            frmSys.Show();
        }
        private void tabList_SelectedIndexChanged(object sender, EventArgs e)
        private void btnMybatis_Click(object sender, EventArgs e)
        {
            string tab = this.tabList.SelectedItem as string;
            List<TabInfo> tabs = (from p in _list where p.tab == tab orderby p.num select p).ToList<TabInfo>();
            this.dgvTab.DataSource = new BindingList<TabInfo>(tabs);
            if (tabs != null && tabs.Count > 1)
            {
                this.dgvTab.Rows[1].Selected = true;
                this.dgvTab.CurrentCell = this.dgvTab.Rows[1].Cells[0];
            }
            FrmMyBatisPlus mybatis = new FrmMyBatisPlus();
            mybatis.Show();
        }
        private void selectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                this.tabList.SetSelected(i, true);
            }
        }
        private void selectFlag_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                bool flag = this.tabList.GetSelected(i);
                this.tabList.SetSelected(i, !flag);
            }
        }
        private void selectNone_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.tabList.Items.Count; i++)
            {
                this.tabList.SetSelected(i, false);
            }
        }
        #endregion
        #region 生成 Mapper.Xml
        private void mapperXml_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateMapperXml(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GenerateMapperXml(string name, List<TabInfo> tabs)
        {
            string tabName = this.txtTabNS.Text.Trim() + name;
            name = name.Replace(this.txtTabPre.Text, "");
            string shortName = NameConvert(name, true);
            string mapperNS = this.txtMapperNS.Text.Trim();
            string mapperName = shortName + "Mapper";
            string entityNS = this.txtEntityNS.Text.Trim();
            string entityName = shortName + "Entity";
            int idx = this.dgvTab.CurrentRow.Index;
            TabInfo selectTabInfo = tabs[idx];
            string colType = GetJavaType(selectTabInfo);
            string colName = NameConvert(selectTabInfo.col, false);
            string testExpr = colName + " != null";
            string testWhere = selectTabInfo.col + (colType == "String" ? " like " : " = ") + "#{" + colName + "}";
            string insertCols = GetInsertCols(tabs);
            string insertVal = GetInsertVal(tabs);
            string insertVals = GetInsertVals(tabs);
            string updateVal = GetUpdateVal(tabs);
            string updateVals = GetUpdateVals(tabs);
            string xml = File.ReadAllText(Path.Combine(baseDir, "Template\\Mapper.xml"));
            xml = xml
                .Replace("{mapperNS}", mapperNS)
                .Replace("{mapperName}", mapperName)
                .Replace("{tabName}", tabName)
                .Replace("{testExpr}", testExpr)
                .Replace("{testWhere}", testWhere)
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{insertCols}", insertCols)
                .Replace("{insertVal}", insertVal)
                .Replace("{insertVals}", insertVals)
                .Replace("{updateVal}", updateVal)
                .Replace("{updateVals}", updateVals);
            string path = Path.Combine(baseDir, "Generate");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = shortName + "Mapper.xml";
            File.WriteAllText(Path.Combine(path, fileName), xml);
        }
        private static string NameConvert(string name, bool firstUpper)
        {
            string[] strs = name.Split(new char[] { '_' });
            string str = "";
            for (int i = 0, c = strs.Length; i < c; i++)
            {
                if (i == 0 && !firstUpper)
                {
                    str += strs[i];
                    continue;
                }
                str += ToUpperFirst(strs[i]);
            }
            return str;
        }
        public static string ToUpperFirst(string str)
        {
            return Regex.Replace(str, @"^\w", t => t.Value.ToUpper());
        }
        public string GetInsertCols(List<TabInfo> tabs)
        {
            List<string> excluds = this.txtInsert.Text.Trim().Split(new char[] { ',' }).ToList<string>();
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                if (excluds.Contains(ti.col))
                {
                    continue;
                }
                sb.Append(ti.col + ",");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        public string GetInsertVal(List<TabInfo> tabs)
        {
            List<string> excluds = this.txtInsert.Text.Trim().Split(new char[] { ',' }).ToList<string>();
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                if (excluds.Contains(ti.col))
                {
                    continue;
                }
                if (ti.type == "timestamp(6)")
                {
                    sb.Append("now(),");
                    continue;
                }
                sb.Append("#{" + NameConvert(ti.col, false) + "},");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        public string GetInsertVals(List<TabInfo> tabs)
        {
            List<string> excluds = this.txtInsert.Text.Trim().Split(new char[] { ',' }).ToList<string>();
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                if (excluds.Contains(ti.col))
                {
                    continue;
                }
                if (ti.type == "timestamp(6)")
                {
                    sb.Append("now(),");
                    continue;
                }
                sb.Append("#{item." + NameConvert(ti.col, false) + "},");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        public string GetUpdateVal(List<TabInfo> tabs)
        {
            List<string> excluds = this.txtUpdate.Text.Trim().Split(new char[] { ',' }).ToList<string>();
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                if (excluds.Contains(ti.col))
                {
                    continue;
                }
                if (ti.type == "timestamp(6)")
                {
                    sb.Append(ti.col + "=now(),");
                    continue;
                }
                sb.Append(ti.col + "=#{" + NameConvert(ti.col, false) + "},");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        public string GetUpdateVals(List<TabInfo> tabs)
        {
            List<string> excluds = this.txtUpdate.Text.Trim().Split(new char[] { ',' }).ToList<string>();
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                if (excluds.Contains(ti.col))
                {
                    continue;
                }
                if (ti.type == "timestamp(6)")
                {
                    sb.Append(ti.col + "=now(),");
                    continue;
                }
                sb.Append(ti.col + "=#{item." + NameConvert(ti.col, false) + "},");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        private static void OpenFolder(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath)) return;
            Process process = new Process();
            ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
            psi.Arguments = folderPath;
            process.StartInfo = psi;
            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                process.Close();
            }
        }
        #endregion
        #region 生成 Mapper.java
        private void mapperJava_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateMapperJava(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GenerateMapperJava(string name, List<TabInfo> tabs)
        {
            name = name.Replace(this.txtTabPre.Text, "");
            string shortName = NameConvert(name, true);
            string mapperNS = this.txtMapperNS.Text.Trim();
            string entityNS = this.txtEntityNS.Text.Trim();
            string mapperName = shortName + "Mapper";
            string entityName = shortName + "Entity";
            string bak = tabs[0].desc.Replace("表", "");
            int idx = this.dgvTab.CurrentRow.Index;
            TabInfo selectTabInfo = tabs[idx];
            string colType  = GetJavaType(selectTabInfo);
            string colName = NameConvert(selectTabInfo.col, false);
            string queryCol = colType + " " + colName;
            string colBak = selectTabInfo.bak;
            string xml = File.ReadAllText(Path.Combine(baseDir, "Template\\Mapper.java"));
            xml = xml
                .Replace("{mapperNS}", mapperNS)
                .Replace("{mapperName}", mapperName)
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{colName}", colName)
                .Replace("{colBak}", colBak)
                .Replace("{bak}", bak)
                .Replace("{queryCol}", queryCol);
            string path = Path.Combine(baseDir, "Generate");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = shortName + "Mapper.java";
            File.WriteAllText(Path.Combine(path, fileName), xml);
        }
        private string GetJavaType(TabInfo ti)
        {
            string type = ti.type.Split(new char[] { '(' })[0];
            switch (type)
            {
                case "timestamp":
                    return "Timestamp";
                case "float4": // float
                    return "Float";
                case "float8": // double
                    return "Double";
                case "bool": // boolean
                    return "Boolean";
                case "numeric":
                    return "BigDecimal";
                case "int8": // long
                    return "Long";
                case "int2":
                case "int4": // int
                    return "Integer";
                default:
                    return "String";
            }
        }
        private String GetType(TabInfo ti)
        {
            string type = ti.type.Split(new char[] { '(' })[0];
            switch (type)
            {
                case "timestamp":
                    return "Timestamp";
                case "float4":
                    return "float";
                case "float8":
                    return "double";
                case "bool":
                    return "boolean";
                case "numeric":
                    return "BigDecimal";
                case "int8":
                    return "long";
                case "int2":
                case "int4":
                    return "int";
                default:
                    return "String";
            }
        }
        #endregion
        #region 生成 Entity.java
        private void entityJava_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateEntityJava(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GenerateEntityJava(string name, List<TabInfo> tabs)
        {
            name = name.Replace(this.txtTabPre.Text, "");
            string shortName = NameConvert(name, true);
            string entityNS = this.txtEntityNS.Text.Trim();
            string entityName = shortName + "Entity";
            string bak = tabs[0].desc.Replace("表", "");
            long uid = (long)Math.Floor((new Random()).NextDouble() * 1000000000000000000D);
            int idx = this.dgvTab.CurrentRow.Index;
            TabInfo selectTabInfo = tabs[idx];
            string xml = File.ReadAllText(Path.Combine(baseDir, "Template\\Entity.java"));
            xml = xml
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{bak}", bak)
                .Replace("{uid}", uid.ToString());
            StringBuilder sb = new StringBuilder();
            foreach (TabInfo ti in tabs)
            {
                string type = GetType(ti);
                string colName = NameConvert(ti.col, false);
                sb.Append("\r\n    private " + type + " " + colName + ";\r\n");
            }
            sb.Append("\r\n    public " + entityName + "() {\r\n    }\r\n");
            foreach (TabInfo ti in tabs)
            {
                string type = GetType(ti);
                string col1 = NameConvert(ti.col, true);
                string col2 = NameConvert(ti.col, false);
                sb.Append("\r\n    public " + type + " get" + col1 + "() {\r\n        return " + col2 + ";\r\n    }\r\n");
                sb.Append("\r\n    public void set" + col1 + "(" + type + " " + col2 + ") {\r\n        this." + col2 + " = " + col2 + ";\r\n    }\r\n");
            }
            sb.Append("}\r\n");
            string path = Path.Combine(baseDir, "Generate");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            sb.Insert(0, xml);
            string fileName = shortName + "Entity.java";
            File.WriteAllText(Path.Combine(path, fileName), sb.ToString());
        }
        #endregion
        #region 生成 Service.java
        private void serviceJava_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateServiceJava(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GenerateServiceJava(string name, List<TabInfo> tabs)
        {
            name = name.Replace(this.txtTabPre.Text, "");
            string shortName = NameConvert(name, true);
            string mapperNS = this.txtMapperNS.Text.Trim();
            string entityNS = this.txtEntityNS.Text.Trim();
            string serviceNS = this.txtServiceNS.Text.Trim();
            string mapperName = shortName + "Mapper";
            string minMapperName = NameConvert(name, false) + "Mapper";
            string entityName = shortName + "Entity";
            string serviceName = shortName + "Service";
            string bak = tabs[0].desc.Replace("表", "");
            int idx = this.dgvTab.CurrentRow.Index;
            TabInfo selectTabInfo = tabs[idx];
            string colType = GetJavaType(selectTabInfo);
            string colName = NameConvert(selectTabInfo.col, false);
            string queryCol = colType + " " + colName;
            //string where = isString ? "\r\n        " + colName + " = \"%\" + (StringHelper.isNull(" + colName + ") ? \"\" : " + colName + ".trim()) + \"%\";\r\n" : "";
            string where = colType == "String" ? "\r\n        " + colName + " = StringHelper.isNull(" + colName + ") ? null : \"%\" + " + colName + ".trim() + \"%\";\r\n" : "";
            string xml = File.ReadAllText(Path.Combine(baseDir, "Template\\Service.java"));
            xml = xml
                .Replace("{mapperNS}", mapperNS)
                .Replace("{mapperName}", mapperName)
                .Replace("{minMapperName}", minMapperName)
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{serviceNS}", serviceNS)
                .Replace("{serviceName}", serviceName)
                .Replace("{bak}", bak)
                .Replace("{queryCol}", queryCol)
                .Replace("{colName}", colName)
                .Replace("{where}", where);
            string path = Path.Combine(baseDir, "Generate");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = shortName + "Service.java";
            File.WriteAllText(Path.Combine(path, fileName), xml);
        }
        #endregion
        #region 生成 Controller.java
        private void controllerJava_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateControllerJava(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GenerateControllerJava(string name, List<TabInfo> tabs)
        {
            name = name.Replace(this.txtTabPre.Text, "");
            string shortName = NameConvert(name, true);
            string mapperNS = this.txtMapperNS.Text.Trim();
            string entityNS = this.txtEntityNS.Text.Trim();
            string serviceNS = this.txtServiceNS.Text.Trim();
            string controllerNS = this.txtControllerNS.Text.Trim();
            string apiTag = this.txtApiTag.Text.Trim();
            string mapperName = shortName + "Mapper";
            string entityName = shortName + "Entity";
            string serviceName = shortName + "Service";
            string minServiceName = NameConvert(name, false) + "Service";
            string controllerName = shortName + "Controller";
            string bak = tabs[0].desc.Replace("表", "");
            string apiName = NameConvert(name, false);
            int idx = this.dgvTab.CurrentRow.Index;
            TabInfo selectTabInfo = tabs[idx];
            string colType = GetJavaType(selectTabInfo);
            string colName = NameConvert(selectTabInfo.col, false);
            string queryCol = colType + " " + colName;
            string colBak = selectTabInfo.bak;
            string xml = File.ReadAllText(Path.Combine(baseDir, "Template\\Controller.java"));
            xml = xml
                .Replace("{mapperNS}", mapperNS)
                .Replace("{mapperName}", mapperName)
                .Replace("{entityNS}", entityNS)
                .Replace("{entityName}", entityName)
                .Replace("{serviceNS}", serviceNS)
                .Replace("{serviceName}", serviceName)
                .Replace("{controllerNS}", controllerNS)
                .Replace("{controllerName}", controllerName)
                .Replace("{minServiceName}", minServiceName)
                .Replace("{queryCol}", queryCol)
                .Replace("{colName}", colName)
                .Replace("{colBak}", colBak)
                .Replace("{colType}", colType)
                .Replace("{apiTag}", apiTag)
                .Replace("{apiName}", apiName)
                .Replace("{bak}", bak);
            string path = Path.Combine(baseDir, "Generate");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = shortName + "Controller.java";
            File.WriteAllText(Path.Combine(path, fileName), xml);
        }
        #endregion
        #region 生成所有文件
        private void generateAll_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.tabList.SelectedItem as string;
                List<TabInfo> tabs = (from p in _list where p.tab == name orderby p.num select p).ToList<TabInfo>();
                GenerateMapperXml(name, tabs);
                GenerateMapperJava(name, tabs);
                GenerateEntityJava(name, tabs);
                GenerateServiceJava(name, tabs);
                GenerateControllerJava(name, tabs);
                string path = Path.Combine(baseDir, "Generate");
                OpenFolder(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
    }
}