使用freemarker自動生成dao,service,model,action,jsp
RT,前段時間讓做一個自動生成的DEMO,然,網上的不明甚以,故摘此篇,部分內容來自網際網路,算是一個大的總結。
這個demo實現的是在web頁面輸入表名列來自動生成一些常用基本的類。
TemplateUtil 類
獲取模板檔案的資訊,並對生成的java檔案的命名及存放路徑進行處理
注:basicAction類是action基類,是讀取現有檔案並做一定出來實現自動生成更改。
SpringTemplateUnits類<span style="white-space:pre"> </span>private String project = null;// 專案名 List fileName = new ArrayList();// 模板檔名 private String tempPath = null;// 模板檔案存放路徑 public TemplateUtil(String url) { setProject(url); setTempPath(url); setFileName(); } public void setProject(String url) { project=url; } public void setTempPath(String tempPath) { this.tempPath = tempPath + "/src/template"; } public String getTempPath() { return tempPath; } public List getFileName() { return fileName; } public void setFileName() { File filePath = new File(tempPath); if (filePath.isDirectory()) { File[] files = filePath.listFiles(); for (File file : files) { fileName.add(file.getName()); } } } public String getProject() { return project; } public String getSavePath(String type, String project, String className) { String newJavaFile = null; if (type.equalsIgnoreCase("dao")) { newJavaFile = project + "/src/dao/" + className + "Dao.java"; } else if (type.equalsIgnoreCase("daoImpl")) { newJavaFile = project + "/src/dao/impl/" + className + "DaoImpl.java"; } else if (type.equalsIgnoreCase("service")) { newJavaFile = project + "/src/service/" + className + "Service.java"; } else if (type.equalsIgnoreCase("serviceImpl")) { newJavaFile = project + "/src/service/impl/" + className + "ServiceImpl.java"; } else if (type.equalsIgnoreCase("entity")) { newJavaFile = project + "/src/model/" + className + ".java"; }else if (type.equalsIgnoreCase("entityHbm")) { newJavaFile = project + "/src/model/" + className + ".hbm.xml"; }else if (type.equalsIgnoreCase("action")) { String tblname=className.substring(3); //去掉tbl的類名 tblname=tblname.substring(0, 1).toUpperCase()+tblname.substring(1); newJavaFile = project + "/src/action/" + tblname + "Action.java"; }else if (type.equalsIgnoreCase("list")) { newJavaFile = project + "/WebRoot/WEB-INF/" + "list.jsp"; }else if (type.equalsIgnoreCase("add")) { newJavaFile = project + "/WebRoot/WEB-INF/" + "add.jsp"; }else if (type.equalsIgnoreCase("detail")) { newJavaFile = project + "/WebRoot/WEB-INF/" + "detail.jsp"; }else if (type.equalsIgnoreCase("edit")) { newJavaFile = project + "/WebRoot/WEB-INF/" + "edit.jsp"; }else if (type.equalsIgnoreCase("basicAction")) { newJavaFile = project + "/src/action/" + "BasicAction.java"; String data=readFileByLines(newJavaFile); //讀取basicAction檔案 String ftlurl = project + "/src/template/basicAction.ftl"; wirteFileByLines(ftlurl,data); //寫ftl模板檔案 }else{ newJavaFile=""; } return new String(newJavaFile); } /** * 根據傳入的表名生成model模型層 * @return {@link Boolean} * @param date 當前日期 */ @SuppressWarnings({ "static-access", "unchecked" }) public void createOneEntity(AutoStartTableEntity aste,String url) { TemplateUtil tu = new TemplateUtil(url); // 模板名 List<String> tempNameList = tu.getFileName(); String className = aste.getTableName(); Map map = new HashMap(); map.put("name", className.toLowerCase()); //全小寫 map.put("Name", className) ; map.put("NAME", className.toUpperCase()); //全大寫 map.put("list", aste.getTableColumn()); map.put("author", "作者"); map.put("ps", "表名"); map.put("date","2015"); String tblname=className.substring(3); //去掉tbl的類名 map.put("tblname", tblname.toLowerCase()); //全小寫action類名 map.put("tblName", tblname.substring(0, 1).toUpperCase()+tblname.substring(1)); for (int j = 0; j < tempNameList.size(); j++) { String tempName = tempNameList.get(j); String type = tempName.substring(0, tempName.lastIndexOf(".")); String newJavaFile = null; newJavaFile = tu.getSavePath(type, url, className); if(newJavaFile.equals("")){ continue; } try { SpringTemplateUnits.templateAppend(tempName, newJavaFile, map, tu.getTempPath()); System.out.println("已建立"+className); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } } } /** * 讀basicAction檔案返回字串 * @param filestr * @return */ public String readFileByLines(String filestr) { BufferedReader reader = null; String str=""; try { System.out.println("以行為單位讀取檔案內容,一次讀一整行:"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(filestr),"UTF-8")); String tempString = null; int line = 1; // 一次讀入一行,直到讀入null為檔案結束 while ((tempString = reader.readLine()) != null) { tempString+="\r\n"; // 顯示行號 if(tempString.equals("\t//自動生成表\r\n")){ tempString+="\
[email protected](name = ${Name}Service.${NAME}_SERVICE_IMPL)\r\n"; tempString+="\tprotected ${Name}Service ${tblname}ser;\r\n"; } if(tempString.equals("//自動生成匯入區域\r\n")){ tempString+="import service.${Name}Service;\r\n"; } System.out.println("line " + line + ": " + tempString); str+=tempString; line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return str; } /** * 寫ftl模板檔案 * @param filestr * @param data */ public void wirteFileByLines(String filestr,String data) { try { File file =new File(filestr); if(file.exists()){ file.delete(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); BufferedWriter bufferWritter = new BufferedWriter(write); bufferWritter.write(data); bufferWritter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("File Wirte Done"); }
該檔案提供生成java檔案的介面
<span style="white-space:pre"> </span>public static String pageEncoding = "UTF-8"; @SuppressWarnings("unchecked") public static boolean templateAppend(String ftlName, String targetFileName, Map map, String relPath) throws IOException, TemplateException { init(ftlName, targetFileName, map, relPath); return true; } @SuppressWarnings("unchecked") public static void init(String ftl, String targetName, Map map, String relPath) throws IOException, TemplateException { Configuration freemarkerCfg = new Configuration(); freemarkerCfg.setDirectoryForTemplateLoading(new File(relPath)); Locale ss=Locale.getDefault(); freemarkerCfg.setEncoding(Locale.getDefault(), pageEncoding); Template template = freemarkerCfg.getTemplate(ftl, pageEncoding); template.setEncoding("UTF-8"); File temp = new File(targetName); String dir = targetName.substring(0, targetName.lastIndexOf("/") + 1); File dirs = new File(dir); if (!dirs.exists()) { dirs.mkdirs(); } Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(temp), pageEncoding)); template.process(map, out); out.flush(); out.close(); }
模板檔案為.ftl格式,下面是model示例,註解是model實現的重新啟動tomcat自動建立資料庫中的表。此外,如果想要實現這個功能的話需要配置hibernate配置檔案中,
<prop key="hibernate.hbm2ddl.auto">update</prop>
entity.ftl
package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="${NAME}")
@SuppressWarnings("serial")
public class ${Name} implements Serializable {
private static final long serialVersionUID = 1L;
<#list list as item>
private ${item.colType} ${item.colName};
</#list>
<#list list as item>
<#if item.colName="id">
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
<#elseif item.colName!="id"&&item.colLong="">
@Column(name="${item.colName}",nullable = ${item.colNull} )
<#else>
@Column(name="${item.colName}",length=${item.colLong},nullable = ${item.colNull})
</#if>
public ${item.colType} get${item.colUPName}() {
return ${item.colName};
}
public void set${item.colUPName}(${item.colType} ${item.colName}) {
this.${item.colName} = ${item.colName};
}
</#list>
}
entityHbm.ftl model類xml檔案<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="www.pdwy.model.${Name}" table="${NAME}">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<#list list as item>
<#if item.colName!="id"&&item.colLong="">
<property name="${item.colName}" type="${item.colAllType}">
<column name="${item.colUPERName}" />
</property>
<#elseif item.colName!="id"&&item.colLong!="">
<property name="${item.colName}" type="${item.colAllType}">
<column name="${item.colUPERName}" length="${item.colLong}" />
</property>
</#if>
</#list>
</class>
</hibernate-mapping>
其他模板使用上面示例基本能解決,唯一需要注意的是JSP模板檔案。
眾所周知,jsp一般需要使用到el表示式,而我們的模板中也恰恰使用到el表示式,在生成你的jsp過程中,freemarker會把你jsp中el表示式當做模板中的來使用,這樣就會出現錯誤。如何避免那?把它當做一個普通的字串就好。
使用${r""}格式來轉換。如:${r"${name}"} 看起來很好用不是嗎?
有的時候會碰到需要使用到模板自動生成的欄位再加上jsp固定的字串,這怎麼來實現?${r""} 同樣支援拼接。如:${r"${"}${tblname}${r"."}${item.colName}${r"}"} 看起來很複雜吧.......
在上述類中使用的了我自建立的工具類或者說模型類,它用來記錄在網頁上所填的表的資訊如:列名等等。
AutoStartTableEntity表模型類
private String tableName; //表名
private List<AutoStartColumnEntity> tableColumn; //表列
public AutoStartTableEntity() {
}
public AutoStartTableEntity(String tableName,
List<AutoStartColumnEntity> tableColumn) {
this.tableName = tableName;
this.tableColumn = tableColumn;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<AutoStartColumnEntity> getTableColumn() {
return tableColumn;
}
public void setTableColumn(List<AutoStartColumnEntity> tableColumn) {
this.tableColumn = tableColumn;
}
AutoStartColumnEntity 表中的列模型 private String colName; //列明
private String colType; //列型別
private String colUPName; //首字母大寫列名
private String colUPERName; //全大寫列名
private String colLong; //列長度
private String colAllType; //列全限定型別
private String colNull; //可否為空
private String colJspName; //jsp所用列描述名
public AutoStartColumnEntity() {
}
public AutoStartColumnEntity(String colName, String colType) {
setColName(colName);
setColType(colType);
setColUPName();
}
public String getColName() {
return colName;
}
public void setColName(String colName) {
this.colName = colName.toLowerCase();
}
public String getColType() {
return colType;
}
public void setColType(String colType) {
this.colType = colType;
/**
* 原用於資料庫
if(colType.equals("nvarchar")||colType.equals("varchar")||colType.equals("nchar")||colType.equals("char"))
this.colType="String";
if(colType.equals("datetime")){
this.colType="Date";
}
*/
}
public String getColUPName() {
return colUPName;
}
public void setColUPName() {
this.colUPName=this.colName.substring(0,1).toUpperCase()+this.colName.substring(1);
}
public String getColLong() {
return colLong;
}
public void setColLong(String colLong) {
this.colLong = colLong;
}
public String getColUPERName() {
return colUPERName;
}
public void setColUPERName() {
this.colUPERName=this.colName.toUpperCase();
}
public String getColAllType() {
return colAllType;
}
public void setColAllType() {
this.colAllType = "java.lang."+colType;
if(colType.equals("Date")){
this.colAllType="java.util.Date";
}
}
public String getColNull() {
return colNull;
}
public void setColNull(String colNull) {
this.colNull = colNull;
}
public void setColNull() {
if(this.colNull==null||this.colNull.equals("")){
this.colNull="false";
}
}
public String getColJspName() {
return colJspName;
}
public void setColJspName(String colJspName) {
this.colJspName = colJspName;
}
這是我action所做的操作。
public String autoPrint() {
//獲取要生成本地專案所在目錄
String url=super.getParameter("url");
TemplateUtil tu = new TemplateUtil(url);
List<AutoStartColumnEntity> astee=new ArrayList<AutoStartColumnEntity>();
//必要預製操作
for (AutoStartColumnEntity col : aste.getTableColumn()) {
if(col!=null){
col.setColUPERName();
col.setColUPName();
col.setColAllType();
col.setColNull();
astee.add(col);
}
}
aste.setTableColumn(astee);
tu.createOneEntity(aste,url);
return SUCCESS;
}
最後上張頁面圖吧
相關推薦
使用freemarker自動生成dao,service,model,action,jsp
RT,前段時間讓做一個自動生成的DEMO,然,網上的不明甚以,故摘此篇,部分內容來自網際網路,算是一個大的總結。 這個demo實現的是在web頁面輸入表名列來自動生成一些常用基本的類。 TemplateUtil 類 獲取模板檔案的資訊,並對生成的java檔案的命名及存放路
使用Mybatis-Generator自動生成Dao、Model、Mapping相關文件
select let 屬於 url img jdb uid enables 粘貼 Mybatis屬於半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的映射文件,由於手動書寫很容易出錯,我們可以利用Mybatis-Generator來幫我們自動生成文件。
使用Mybatis-Generator自動生成Dao、Model、Mapping相關文件(轉)
rop root github mini -c back fig override creat https://github.com/astarring/mybatis-generator-gui 帶界面版:需要jdk 1.8以上 出處:http:
使用 mybatis-Generator 自動生成DAO、Model、Mapping相關檔案
1、Maven專案 2、配置generatorConfig.xml檔案 3、在pom.xml中配置外掛 2、generatorConfig.xml檔案資訊 <?xml version="1.0" encoding="UTF-8"?> <!DO
Mybatis-Generator自動生成Dao、Model、Mapping檔案
Mybatis屬於半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的對映檔案,由於手動書寫很容易出錯,我們可以利用Mybatis-Generator來幫我們自動生成檔案。 1、相關檔案 由於我使用的是Mysql資料庫,這裡需要再準備一個連線mys
使用Mybatis-Generator自動生成Dao、Model、Mapping相關檔案
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration
【提供原始碼下載】使用Mybatis-Generator自動生成Dao、Model、Mapping相關檔案
其實這個沒什麼,但是能大大加快我們的開發速度。 只需要把一個配置檔案配置好就行, <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//my
使用Mybatis-Generator自動生成Dao、Model、Mapping相關檔案(轉)
下載地址: https://github.com/zouzg/mybatis-generator-gui/releases 使用說明: https://github.com/zouzg/mybatis-generator-gui 下載地址: https://git
搭建:使用Mybatis-Generator自動生成Dao、Model、Mapping相關檔案
使用Mybatis-Generator自動生成Dao、Model、Mapping相關檔案一、在pom.xml中配置<build><plugins><plugin><groupId>org.mybatis.generator<
【Maven學習(七)】----基於Mybatis-Generator自動生成Dao、Model、Mapping檔案
基於Mybatis-Generator自動生成Dao、Model、Mapping檔案 準備工作: 安裝並配置好MyEclipes + Maven 1、配置Maven的pom.xml檔案 在pom.xml新增mybatis-generator外掛: <!-- my
使用MyBatis-Gererator自動生成Dao.Model.Mapping相關文件
less .cn dbcc nat acc git reat logs ping 一。在MyEclipse中使用Maven項目下使用MyBatis-Gererator自動生成Dao.Model.Mapping相關文件 1.關於Mybatis-Generator的下載可以
mybatis自動生成dao, model, mapper xml檔案
用mybatis的時候,手寫xml或model檔案是一個力氣活,所以可以用mybatis-gennerator外掛自動生成mybatis所需要的dao、bean、mapper xml檔案 (原文地址:http://blog.csdn.net/tolcf/article/details/50835
eclipse中根據資料庫自動生成dao、mapper、model
現在程式碼管理基本上是採用Maven管理,Maven的好處此處不多說,大家用百度搜索會有很多介紹,本文介紹一下用Maven工具如何生成Mybatis的程式碼及對映的檔案。 一、配置Maven pom.xml 檔案 在pom.xml增加以下外掛:
MyBatis逆向工程,自動生成dao、實體類、mapper檔案
利用mybatis generator 自動生成生成dao、實體類、mapper檔案 這裡介紹兩種方法: 1、獨立的資料夾的方式,脫離開發工具 2、基於開發工具的方式(Eclipse) 1、獨立的資料夾的方式,脫離開發工具
idea + groovy + mybatis 自動生成 Dao、mappings 和 實體類
背景 在 windows 系統中,idea 在 C:\Users\使用者名稱\.IntelliJIdea2018.2\config\extensions\com.intellij.database\schema 目錄下預設存在如下 Groovy 檔案:Generate POJOs.g
idea 利用maven自動生成dao、dto、mapper檔案
1.在pom檔案中新增maven依賴 <build> <finalName>lottery-common</finalName> <plugins> <plugi
springboot用mybatis-generator自動生成mapper和model以及xml
前言 mybatis是一個半自動的orm(物件關係對映)框架。之所以說它是半自動的,這是因為它需要開發人員編寫sql語句,但是它又可以將java物件對映成sql語句的引數中,也可以將sql語句執行的結果對映到java物件。相對於hibernate來說,使用mybatis可以
Mybatis Generator(MBG)自動生成dao,entity ,mapper.xml對映
1.在pom.xml中引入依賴 <!--mybatis-generator 自動生成工具--> <dependency> <groupId>org.mybatis.generator
hibernate自動生成dao
hibernate 用 MyEclipse, 就有必要把 MyEclipse 快速開發的功能熟悉一下. 當我們熟悉了
mybatis-generator自動生成dao、mapping、bean配置詳解(轉)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configur