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