開源代碼生成器MyGeneration使用(四) 綜合示例

目標:根據選擇的數據表生成java 實體類,並附帶hibernate註解。模板語言使用C#。

Interface Code代碼:

public class GeneratedGui : DotNetScriptGui
{
	public GeneratedGui(ZeusContext context) : base(context) {}

	//-----------------------------------------
	// The User Interface Entry Point
	//-----------------------------------------
	public override void Setup()
	{
		ui.Title = "Generate entity class with hibernate annotations";
		ui.Width = 350;
		ui.Height = 430;

		String sOutputPath = "";
		if (input.Contains("defaultOutputPath")) 
		{
			sOutputPath = input["defaultOutputPath"].ToString();
		}

		// Display and errors here
		GuiLabel lblError = ui.AddLabel("lblError", "", "");
		lblError.ForeColor = "Red";

		// Setup Folder selection input control.
		GuiLabel lblPath = ui.AddLabel("lblPath", "選擇輸出路徑:", "Select the output path in the field below.");
		GuiTextBox outpath = ui.AddTextBox("txtPath", sOutputPath, "Select the Output Path.");
		GuiFilePicker btnSelectPath = ui.AddFilePicker("btnPath", "選擇", "Select the Output Path.", "txtPath", true);

		// Setup Database selection combobox.
		GuiLabel label_d = ui.AddLabel("lblDatabases", "選擇數據庫:", "Select a database in the dropdown below.");
		GuiComboBox cmbDatabases = ui.AddComboBox("cmbDatabase", "Select a database.");

		// Setup Tables selection multi-select listbox.
		GuiLabel label_t = ui.AddLabel("lblTables", "選擇表:", "Select tables from the listbox below.");
		GuiListBox lstTables = ui.AddListBox("lstTables", "Select tables.");
		lstTables.Height = 150;

		// 綁定數據庫列表到combobox
		setupDatabaseDropdown(cmbDatabases, lblError);
		cmbDatabases.AttachEvent("onchange", "cmbDatabases_onchange");

		ui.ShowGui = true;
	}
	
	private void setupDatabaseDropdown(GuiComboBox cmbDatabases,GuiLabel lblError)
	{
		try 
		{	
			if (MyMeta.IsConnected) 
			{
				cmbDatabases.BindData(MyMeta.Databases);
				if (MyMeta.DefaultDatabase != null) 
				{
					cmbDatabases.SelectedValue = MyMeta.DefaultDatabase.Name;
					bindTables(cmbDatabases.SelectedValue);
				}

				lblError.Text = "";
			}
			else
			{
				lblError.Text = "請先設置正確的數據庫連接";
			}
		}
		catch (Exception ex) 
		{
			lblError.Text=ex.Message;
		}
	}

	private void bindTables(string sDatabase)
	{
		GuiLabel lblError = ui["lblError"] as GuiLabel;
		//int count = 0;

		GuiListBox lstTables = ui["lstTables"] as GuiListBox;
	
		try 
		{	
			IDatabase db = MyMeta.Databases[sDatabase];
			lstTables.BindData(db.Tables);

			lblError.Text = "";
		}
		catch (Exception ex) 
		{
			lblError.Text=ex.Message;
		}
	}

	public void cmbDatabases_onchange(GuiComboBox control)
	{
		GuiComboBox  cmbDatabases = ui["cmbDatabase"] as GuiComboBox;
		bindTables(cmbDatabases.SelectedText);
	}

}
  使用C#時製作界面還有一種方法是製作一個普通的Form界面,直接調用該界面即可。在Form中傳入dbRoot myMeta, IZeusInput zeusInput兩個對象,確定按鈕事件將輸入值賦給input就行了。以下示例代碼 定義了窗體FrmGui類,Setup方法直接調用該窗體即可
<%#REFERENCE System.Windows.Forms.dll, System.Drawing.dll,mscorlib.dll%>
<%#NAMESPACE System, System.Windows.Forms, System.Drawing, System.Text.RegularExpressions,System.Collections%>
public class GeneratedGui : DotNetScriptGui
{
  public GeneratedGui(ZeusContext context) : base(context) {}

  public override void Setup()
  {
     FrmGui form = new FrmGui(MyMeta, input); 
     if (form.ShowDialog() != DialogResult.OK) 
     {
       ui.IsCanceled = true;
     }
   }
}

public class FrmGui : Form
    {
	//...定義winform控件...
		
        private dbRoot myMeta;
        private IZeusInput zeusInput;

        public FrmGui(dbRoot myMeta, IZeusInput zeusInput)
        {
	    this.myMeta    = myMeta;
	    this.zeusInput = zeusInput;
            InitializeComponent();
        }
       private void btnOk_Click(object sender, EventArgs e)
       {
          this.zeusInput["databaseName"] = database.Name;
          this.zeusInput["tableNames"] =tableArray;
          this.zeusInput["outputPath"] = outputPath.Text;
            ....
        }
      ....其他方法省略
   }
這種方法適合界面比較複雜的場合,直接在visual Studio中做好再拷貝過來就行了。

Template Code:

<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization%><%
public class GeneratedTemplate : DotNetScriptTemplate
{
	private ArrayList selectedTables;
	private string dbName;
	private string exportPath;
	private string _className;	//當前類名
	private string _tableName;	//當前表名
	private string _tableNameAlias;//當前表別名
	string _fileName;
	
	public GeneratedTemplate(ZeusContext context) : base(context) {}

	//---------------------------------------------------
	// Render() is where you want to write your logic    
	//---------------------------------------------------
	public override void Render()
	{
		dbName=input["cmbDatabase"].ToString();
        selectedTables=input["lstTables"] as ArrayList;
        exportPath=input["txtPath"].ToString();
		foreach(string _newTable in selectedTables)
		{
			ITable _workingTable = MyMeta.Databases[dbName].Tables[_newTable];
			_tableName = _workingTable.Name;
			_tableNameAlias=_workingTable.Alias.Replace( " ", "" );
			_className =DnpUtils.SetPascalCase( _tableNameAlias );

			GenerateEntity( _workingTable.Columns );
		}
	}
	//成員變量字符串模板
	string memberVarFmt="private {0} {1};";
	//get方法模板
	string getMethodFmt = "public {0} get{1}()\r\n\t{{\r\n\t\t return this.{2};\r\n\t}}";
	//set方法模板
        string setMethodFmt = "public void set{0}({1} _{2})\r\n\t{{\r\n\t\tthis.{2}=_{2};\r\n\t}}";
	
	//生成實體類
	private void GenerateEntity( IColumns Columns )
	{
		output.tabLevel=0;
		output.writeln("package com.entity;");
		output.writeln("");
		//生成導入註解包
		output.writeln("import javax.persistence.Entity;");
		output.writeln("import javax.persistence.Id;");
		output.writeln("import javax.persistence.GeneratedValue;");
		output.writeln("import javax.persistence.GenerationType;");
		output.writeln("import javax.persistence.JoinColumn;");
		output.writeln("import javax.persistence.ManyToOne;");
		output.writeln("import javax.persistence.Table;");
		output.writeln("");
		output.writeln("@Entity");
		if(!_className.Equals(_tableNameAlias,StringComparison.OrdinalIgnoreCase))
		{
			output.writeln("@Table(name=\""+_tableName+"\")");
		}
		output.writeln("public class "+_className+" implements java.io.Serializable {");
		output.tabLevel=1;
		
		if( Columns.Count > 0 )
		{
			string tmpName,tmpProperty,tmpType;
			//生成成員變量定義
			foreach( IColumn field in Columns )
			{
				tmpName=DnpUtils.SetCamelCase(field.Alias.Replace( " ", "" ));
				if( field.IsInForeignKey && !field.IsInPrimaryKey ){
					tmpType=DnpUtils.SetPascalCase(field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ));
				}else{
					tmpType=field.LanguageType;
				}

				output.autoTabLn(createColumnAnnotations(field));//hibernate註解
				output.autoTabLn(string.Format(memberVarFmt,tmpType,tmpName));	//成員變量
			}
			output.writeln("");
			output.autoTabLn("//getter and setter");
			//生成公共get,set方法
			foreach( IColumn field in Columns )
			{
				tmpName=DnpUtils.SetCamelCase(field.Alias.Replace( " ", "" ));
				tmpProperty=DnpUtils.SetPascalCase(field.Alias.Replace( " ", "" ));
				if( field.IsInForeignKey && !field.IsInPrimaryKey ){
					tmpType=DnpUtils.SetPascalCase(field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ));
				}else{
					tmpType=field.LanguageType;
				}
				output.autoTabLn(string.Format(getMethodFmt,tmpType,tmpProperty,tmpName));//get
				output.autoTabLn(string.Format(setMethodFmt,tmpProperty,tmpType,tmpName));//set
			}
		}
		output.write("}");
		//輸出文件
		_fileName = _className + ".java";
		output.save( Path.Combine(exportPath, _fileName), false );
		output.clear();
	}
	
	StringBuilder annot = new StringBuilder();
	//生成實體類列的註解
	private string createColumnAnnotations(IColumn field)
	{
		annot.Length=0;//清空
		if(field.IsInPrimaryKey)	//主鍵
		{
			annot.AppendLine("@Id");
			if(field.IsAutoKey)
				annot.AppendLine("\t@GeneratedValue(strategy=GenerationType.AUTO)");
		}
		if( field.IsInForeignKey && !field.IsInPrimaryKey )	//外鍵,多對一關係
		{
			annot.AppendLine("@ManyToOne");
			annot.Append("\t@JoinColumn(name=\"").Append(field.Name).Append("\")");
		}
		if(!field.IsInForeignKey)
		{
			annot.Append("@Column(name=\"").Append(field.Name).Append("\"");
			if(!field.IsNullable){
				annot.Append(",nullable=false");
			}
			if(field.LanguageType=="String"){
				annot.Append(",length=").Append(field.CharacterMaxLength);
			}
			annot.Append(')');
		}
		return annot.ToString();
	}
}
%>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章