您的位置:首页 > 数据库 > MySQL

CodeSmith代码自动生成器 JAVA模版的制作---CodeSmith+MySQL+MyEclipse 10

2015-03-26 11:00 155 查看
自己做的时候没有找到详细的JAVA模版 大多都是C#的,所以自己记录下,还有很多不懂的,日后慢慢琢磨吧

以Entity实例为例子,直接贴代码,把自己认为比较闹心的地方画个圈圈标记出来

首先 设计模版
创建一个cst文件叫做entity.cst,

<%@ Template Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" %><%--声明模版--%>

<%--需要加载的组件--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer"%>

<%--参数集--%>
<%@ Property Name="NameSpace" Type="System.String" Default="ProjectManage" Category="Text" Description="Namespace for this class" %>
<%@ Property Name="ClassName" Type="System.String" Default="Project" Category="Other" Description="" %>
<%@ Property Name="ObjectName" Type="System.String" Default="projext" Category="Other" %>
<%@ Property Name="TypeName" Type="System.String" Default="projext" Category="Other" %>
<%@ Property Name="TableName" Type="System.String" Default="projext" Category="Other" %>
<%@ Property Name="BaseName" Type="System.String" Default="projext" Category="Other" %>
<%@ Property Name="Table" DeepLoad="True" Type="TableSchema" Optional="False" Category="01. Getting Started - Required" Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated."%>

<%@ Assembly Src="Utility.cs" %><%--自定义方法,用于处理数据库 数据表的下划线,tb,首字母大写--%>
<%@ Import Namespace="Common" %>
<%-- 启用 MAP方式 System-JavaAlias 将数据类型转换成JAVA数据类型 转换成C#要启用System-CSharpAlias --%>
<%@ Map Name="JavaAlias" Src="System-JavaAlias.csmap" Description="Oracle to Java Type Map" %>

<%@ Import Namespace="System.IO" %>

package <%= NameSpace%>.entity;
// default package

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* <%= NameSpace%> entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name="<%= TableName%>"<%--文件名--%>
,catalog="<%= BaseName%>"<%--数据库名--%>
)

public class <%= ClassName%> implements java.io.Serializable {
<%foreach(ColumnSchema col in Table.Columns){ %><%--获取表的字段 声明字段--%>
<% if (col.Name == "CreatedTime" || col.Name == "UpdatedTime" || col.Name == "TS") { %>
private Timestamp <%= StringUtil.ToCamelCase(col.Name) %>;
<% } %>
<% else{%>
private <%= JavaAlias[col.SystemType.FullName]%> <%= StringUtil.ToCamelCase(col.Name) %>;
<%}%><%--由于时间类型由datatime转换成Timestamp总是不成功 万不得已做的特殊处理--%>
<% } %>
<%foreach(ColumnSchema col in Table.Columns){ %><%--获取表的字段 声明get set方法--%>
<% if (col.Name == "CreatedTime" || col.Name == "UpdatedTime" || col.Name == "TS") { %>

@Column(name="<%= StringUtil.ToCamelCase(col.Name) %>")
public Timestamp get<%= StringUtil.ToPascalCase(col.Name) %>() {
return this.<%= StringUtil.ToCamelCase(col.Name)%>;
}

public void set<%= StringUtil.ToPascalCase(col.Name) %>( Timestamp <%= StringUtil.ToCamelCase(col.Name)%>) {
this.<%= StringUtil.ToCamelCase(col.Name)%> = <%= StringUtil.ToCamelCase(col.Name)%>;
}
<% } %>
<% else{%>

<%= col.IsPrimaryKeyMember ? "@Id @GeneratedValue" : ""%> <%--判断如果是主键 返回该注解(用于在JAVA中映射)--%>
<% if(col.SystemType.FullName == "System.String"){%> <%--判断是否为string类型 如果是 返回长度 返回该注解(用于在JAVA中映射)--%>
<% if(col.AllowDBNull==false){%> <%--判断是否允许为空 如果不允许 false 返回该注解(用于在JAVA中映射)--%>
@Column(name="<%= col.Name %>",length="<%= col.Size %>",nulllable="<%= col.AllowDBNull%>")
<%} %>
<%else{%>
@Column(name="<%= col.Name %>",length="<%= col.Size %>")
<%} %>
<%} %>
<% else{ %>
<% if(col.AllowDBNull==false){%>
@Column(name="<%= col.Name %>",nulllable="<%= col.AllowDBNull%>")
<%} %>
<%else{%>
@Column(name="<%= col.Name %>")
<%} %>
<%}%>
public <%= JavaAlias[col.SystemType.FullName]%> get<%= StringUtil.ToPascalCase(col.Name) %>() {
return this.<%= StringUtil.ToCamelCase(col.Name)%>;
}

public void set<%= StringUtil.ToPascalCase(col.Name) %>( <%= JavaAlias[col.SystemType.FullName]%> <%= StringUtil.ToCamelCase(col.Name)%>) {
this.<%= StringUtil.ToCamelCase(col.Name)%> = <%= StringUtil.ToCamelCase(col.Name)%>;<%}%>
}
<% } %>
}

创建自定义函数Utility.cs

using System;
using System.Text;
using CodeSmith.Engine;
using SchemaExplorer;
using System.ComponentModel;
using System.Data;

namespace Common
{
/**//// <summary>
/// TemplateRule
/// </summary>
public static class Utility
{
public static string GetClassName(string tableName)
{
string className = tableName.Replace("_", "");
string[] array = tableName.Split('_');

if (array.Length > 1)
{
/*if (array[0] == array[1])
{
className = array[0];
}
else if (array[0] == "Dict" || array[0] == "Wiki" || array[0] == "Ask" || array[0] == "Forum" || array[0] == "Class")
{
className = array[1];
}*/

if (array.Length == 2)
{
className = StringUtil.ToPascalCase(array[1]);
}
else if (array.Length == 3)
{
className = StringUtil.ToPascalCase(array[1]) + StringUtil.ToPascalCase(array[2]);
}
else if (array.Length == 4)
{
className = StringUtil.ToPascalCase(array[1]) + StringUtil.ToPascalCase(array[2]) + StringUtil.ToPascalCase(array[3]);
}
}

return className;
}

public static string GetTypeName(string typeName)
{
typeName = StringUtil.ToPascalCase(typeName);
return typeName;
}

public static string GetObjectName(string tableName)
{
string className = tableName.Replace("_", "");
string[] array = tableName.Split('_');

if (array.Length > 1)
{
if (array.Length == 2)
{
className = array[1];
}
else if (array.Length == 3)
{
className = array[1] + array[2];
}
else if (array.Length == 4)
{
className =array[1] + array[2] + array[3];
}
}
return className;
}

public static string GetProjectName(string tableName)
{
string[] array = tableName.Split('_');

if (array.Length == 2)
{
if (array[0] == "Wiki")
{
return "Wiki";
}
else if (array[0] == "Dict")
{
return "Dict";
}
else if (array[0] == "Ask")
{
return "Ask";
}
else if (array[0] == "Forum")
{
return "Forum";
}
else if (array[0] == "Class")
{
return "Class";
}
}

return "Dialect";
}
}

生成模版 创建cst文件 make_entity.cst

<%--声明模版--%>
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8"%>

<%--注册提供用户自定义连接的属性--%>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="01. Getting Started - Required" Description="Database that the tables views, and stored procedures should be based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, the Entire Database will then be generated." %>

<%--注册设计模版--%>
<%@ Register Name="EntityTemplate" Template="entity.cst" MergeProperties="Flase" ExcludeProperties=""%>

<%@ Assembly Src="Utility.cs" %><%--自定义方法,用于处理数据库 数据表的下划线,tb,首字母大写--%>
<%@ Import Namespace="Common" %>
<%@ Import Namespace="System.IO" %>

<%--需要加载的组件--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>

<script runat="template">
//定义输出目录
private string Directory = String.Empty;

[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] //声明属性

public string OutputDirectory
{
get
{
return Directory;
}
set
{
if (value.EndsWith("\\")) value = value.Substring(0, value.Length -1);
Directory = value;
}
}
</script>

<script runat="template">
private void MakeTemplate()
{
CodeTemplate template = new AuthenServiceTemplate();//得到一个设计模版对象
string type="entity";
string elementName="{0}{1}";//文件名
foreach(TableSchema table in this.SourceDatabase.Tables)//获取数据库中的每一张表
{
string[] array = this.SourceDatabase.Database.Name.Split('_');//去下划线
string className = Utility.GetClassName(table.Name);//字段格式转换
string objectName=Utility.GetObjectName(table.Name);
string typeName=Utility.GetTypeName(type);
string projectName = array[1]+".";
string FileDirectory = OutputDirectory+ "\\"+ string.Format(elementName,className,(".java"));//输出路径及文件格式

//为涉及模版对象传入参数
template.SetProperty("SourceTable", table);
template.SetProperty("NameSpace", projectName);
template.SetProperty("ClassName", className);
template.SetProperty("TableName", table.Name);
template.SetProperty("ObjectName", objectName);
template.SetProperty("BaseName", this.SourceDatabase.Database.Name);

//生成模板
template.SetProperty("Table",table);
//文件输出
template.RenderToFile(FileDirectory,true);
Debug.WriteLine(FileDirectory +" 创建成功.");
}
}
</script>

<%
this.MakeTemplate();//调用
%>

最后绑定数据库,制定数据输出路径Generate一下,就可以了

数据类型转换的时候一度不想做了,真的烦,各种类型不一致,还找不到统一转换的方法,尝试一个一个做判断,脑子里面就一个想法,去死去死去死好了,不过弄到现在

差不多了心情就就愉快了,路漫漫其修远兮~吾将上下左右东南西北而求索......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: