开源代码生成器MyGeneration使用(四) 综合示例

12 篇文章 0 订阅
4 篇文章 0 订阅

目标:根据选择的数据表生成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();
	}
}
%>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyGeneration 是一款不错的ORM和代码生成工具,它基于模板(Template)工作,安装好MyGeneration 后自了很多模板,并且提供在线模板库提供模板升级和允许用户自定义模板MyGeneration模板可以用C#, VB.NET, JScript, and VBScript编写。使用MyGeneration 可以为Gentle.NET, Opf3, NHibernate等生成ORM架构或ORM文件,为多种数据库生成存储过程,为.Net项目生成C#、VB.NET 程序代码,PHP、HTML等页面代码。 MyGeneration 具有以下的特性: 1.支持多种数据库 Microsoft SQLServer Oracle IBM DB2 Microsoft Access MySQL PostgreSQL Firebird Interbase SQLite VistaDB Advantage IBM iSeries CSV & other delimited text files 2.支持重用和include文件 3.Ability to single step through all templates regardless of language. (单步调试?) 4.支持为模板输入自定义用户界面,包括winForm程序。 5.提供cmd命令行工具(ZuesCmd.Exe)和GUI(Project)工具. 6.提供强大的原数据 API(MyMeta)访问你的数据库里的原数据。 7.提供Unicode、语法高亮、查找、替换等功能的强大文本编辑器。 8.支持插件(Intrinsic Objects)扩展模板的功能。 9.支持MyMeta meta-data providers插件 10.Dockable windows.(不懂) 11.提供动态的可重写的数据类型映射。从数据库类型到MyGeneration的数据提供者类型到代码类型。 12.支持用户自定义原数据。 13.支持表、字段名、参数等重命名。 14.可以使用Gentle.NET, Opf3, NHibernate的模板。 15.支持在线帮助、模板升级和论坛。 二、myGeneration里的文件 目录: Architectures\ Contains dOOdads and any other MyGeneration sponsered frameworks/architectures. GeneratedCode\ 默认生成代码的存放位置。 Settings\ 配置文件存放目录。配置文件是各种.xml文件。 Templates\ 默认模板存放目录。 可执行文件: MyGeneration.exe 打开window界面 ZeusCmd.exe 打开命令行界面 uninstall.exe 各种帮助文件: ~\.chm 各种数据库驱动文件: ~\.dll 配置文件: DockManager.Config Settings\DefaultSettings.xml 存放默认设置。 Settings\DbTargets.xml 存放数据库到数据提供者数据类型的映射配置 Settings\Languages.xml 存放数据提供者到目标语言的数据类型映射配置 Settings\ScintillaNET.xml 存放语法高亮显示的对应关系的设置信息。 Settings\ZeusConfig.xml 三、缺点 只支持单表,复杂的查询还要先写视图

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值