freemarker 生成java_利用FreeMarker自动生成JavaEE项目中的dao、business、service层代码...

本文介绍了一个利用FreeMarker、XMLReader和SpringTemplateUnits等工具,根据Hibernate逆向工程生成的实体对象,自动生成JavaEE项目的DAO、Business、Service层代码的过程。详细讲述了实现步骤,包括读取XML配置、解析实体类信息、应用模板生成Java文件,并提供了具体代码示例。

实现目标:

在JavaEE项目中,可以从通过Hibernate的逆向工程,将数据库中的表映射成Java实体对象,现假设映射出来的文件放在包com.rongji.filecenter.persistence中,该包放持久层对象类,包里面有两个文件,一个是FcApp.java,一个是FcApp.hbm.xml.

对于一般的项目,业务相关的文件存放格式为:com.company.project.dao、com.company.project.dao.impl,只有project是变动的,而其他一般保持不变,若现在已知存在如下包路径com.rongji.filecenter.persistence,并且包内含有实体对象的类(.java)及配置文件(.xml),通过运行程序,可以自动在项目中生成包路径:com.rongji.filecenter.dao、com.rongji.filecenter.dao.impl、com.rongji.filecenter.business、com.rongji.filecenter.business.impl、com.rongji.filecenter.service、com.rongji.filecenter.service.impl,并且在包内生成相应的代码!

实现过程:

1、在项目中导入相应的包,FreeMarker需要导入freemark.jar包,有用到Spring、Hibernate需要导入相应的包。

2、编写代码:

《一》XMLReader.java文件,该文件主要用于读取xml配置文件中实体对象的类名、id名

package com.rongji.filecenter.utils;

import java.io.File;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class XMLReader {

private static String fileName = "";

private static File file = null;

public XMLReader() {

}

public XMLReader(String fileName) {

this.file = new

File(fileName);

}

public XMLReader(File file) {

this.file = file;

}

public static String getIdName() {

String id = null;

SAXReader saxReader = new

SAXReader();

try {

Document

document = saxReader.read(file);

Element root

= document.getRootElement();

for (Iterator

iter = root.elementIterator(); iter.hasNext();) {

Element

element = (Element) iter.next();

for

(Iterator iterInner = element.elementIterator(); iterInner

.hasNext();)

{

Element

elementInner = (Element) iterInner.next();

if

(elementInner.getName().equals("id")) {

id

= elementInner.attributeValue("name");

//

System.out.println(id);

break;

}

}

}

} catch (DocumentException e)

{

e.printStackTrace();

}

return id;

}

public static String getClassFullName() {

String className = null;

SAXReader saxReader = new

SAXReader();

try {

Document

document = saxReader.read(file);

Element root

= document.getRootElement();

for (Iterator

iter = root.elementIterator(); iter.hasNext();) {

Element

element = (Element) iter.next();

if

(element.getName().equals("class")) {

className

= element.attributeValue("name");

//

System.out.println(className);

break;

}

}

} catch (DocumentException e)

{

e.printStackTrace();

}

return className;

}

public static String getClassFullName(File

file) {

XMLReader.file = file;

return

getClassFullName();

}

public static String getClassName() {

String className =

getClassFullName();

if (className != null) {

className =

className.substring(className.lastIndexOf(".") + 1,

className.length());

}

return className;

}

public static String getClassName(File file)

{

String className =

getClassFullName(file);

if (className != null) {

className =

className.substring(className.lastIndexOf(".") + 1,

className.length());

}

return className;

}

public static List getAllClassName(File filePath)

{

List list = new

ArrayList();

if (filePath.isDirectory())

{

File[] files

= filePath.listFiles();

for (File

file : files) {

if(file.getName().endsWith(".xml")){

list.add(getClassName(file));

}

}

}

return list;

}

public String changeToLower(String string)

{

String temp = new

String();

if (string != null) {

char oldChar

= string.charAt(0);

char newChar

= (oldChar + "").toLowerCase().charAt(0);

temp =

string.replace(oldChar, newChar);

}

return new String(temp);

}

public String changeToUpper(String string)

{

String temp = new

String();

if (string != null) {

char oldChar

= string.charAt(0);

char newChar

= (oldChar + "").toUpperCase().charAt(0);

temp =

string.replace(oldChar, newChar);

}

return new String(temp);

}

public static File getFile() {

return file;

}

public static void setFile(File file) {

XMLReader.file = file;

}

}

《二》TemplateUtil.java,获取模板文件的信息,并对生成的java文件的命名及存放路径进行处理

package com.rongji.filecenter.utils;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import freemarker.template.TemplateException;

public class TemplateUtil {

private String project = null;// 项目名

List fileName = new ArrayList();// 模板文件名

private String tempPath = null;// 模板文件存放路径

public TemplateUtil() {

setProject();

setTempPath(null);

setFileName();

}

public TemplateUtil(String tempPath) {

setProject();

setTempPath(tempPath);

setFileName();

}

public void setProject() {

String projectname =

System.getProperty("user.dir");

String pn =

projectname.substring(projectname.lastIndexOf('\\') + 1,

projectname.length());

project = pn;

}

public void setTempPath(String tempPath)

{

if (tempPath == null) {

this.tempPath

= System.getProperty("user.dir") + "\\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;

String projectDir =

System.getProperty("user.dir");

if

(type.equalsIgnoreCase("dao")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project + "/dao/"

+

className + "Dao.java";

} else if

(type.equalsIgnoreCase("daoImpl")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project

+

"/dao/impl/" + className + "DaoImpl.java";

} else if

(type.equalsIgnoreCase("business")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project

+

"/business/" + className + "Business.java";

} else if

(type.equalsIgnoreCase("businessImpl")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project

+

"/business/impl/" + className + "BusinessImpl.java";

} else if

(type.equalsIgnoreCase("service")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project

+

"/service/" + className + "Service.java";

} else if

(type.equalsIgnoreCase("serviceImpl")) {

newJavaFile =

projectDir + "/src/com/rongji/" + project

+

"/service/impl/" + className + "ServiceImpl.java";

}

return new

String(newJavaFile);

}

@SuppressWarnings( { "static-access", "unchecked"

})

public void process(String project) {

XMLReader xr = new

XMLReader();

// 类名

List

classNameList = xr.getAllClassName(new File(System

.getProperty("user.dir")

+

"\\src\\com\\rongji\\" +

project + "\\persistence"));

TemplateUtil tu = new

TemplateUtil();

// 模板名

List

tempNameList = tu.getFileName();

for (int i = 0; i

< classNameList.size(); i++) {

String

className = classNameList.get(i);

String idName

= xr.getIdName();

Map map = new

HashMap();

map.put("project",

project);

map.put("name",

xr.changeToLower(className));

map.put("Name",

className);

map.put("Id",

xr.changeToUpper(idName));

map.put("id",

idName);

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, project, className);

try

{

SpringTemplateUnits.templateAppend(tempName,

newJavaFile,

map,

tu.getTempPath());

}

catch (IOException e) {

e.printStackTrace();

}

catch (TemplateException e) {

e.printStackTrace();

}

}

}

}

}

《三》SpringTemplateUnits.java,该文件提供生成java文件的接口

package com.rongji.filecenter.utils;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.util.Locale;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.TemplateException;

public class SpringTemplateUnits {

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));

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();

}

}

其中,模板文件存放在项目的根目录下的template文件夹中,命名格式为dao.ftl、daoImpl.ftl、business.ftl、businessImpl.ftl、service.ftl、serviceImpl.ftl

dao.ftl文件中内容如下:

package com.rongji.${project}.dao;

import com.rongji.${project}.persistence.${Name};

public interface ${Name}Dao {

public ${Name} get${Name}ById(String

${name});

public void save${Name}(${Name} ${name});

}

daoImpl.ftl中的内容如下:

package com.rongji.${project}.dao.impl;

import java.util.List;

import com.rongji.dfish.framework.FrameworkHelper;

import com.rongji.dfish.util.Utils;

import com.rongji.${project}.dao.${Name}Dao;

import com.rongji.${project}.dao.BeansFactory;

import com.rongji.${project}.persistence.${Name};

public class ${Name}DaoImpl implements ${Name}Dao {

private String tblName = "${Name}";

public void save${Name}(${Name} ${name})

{

if (${name} != null) {

String msgId

= ${name}.get${Id}();

if

(Utils.isEmpty(msgId)) {

${name}.set${Id}((FrameworkHelper.getNewId(tblName,

"${id}", "00000001")));

}

BeansFactory.getPubDao().saveObject(${name});

}

}

public FcApp get${Name}ById(String ${id})

{

if (Utils.isEmpty(${id}))

return

null;

List

list = BeansFactory.getPubDao().getQueryList("from " + tblName + "

t WHERE t.id=?", ${id});

if (list != null

&& list.size() > 0)

{

return

(${Name}) list.get(0);

}

return null;

}

}

其他文件略!

实际上,运行的时候,是通过Map的对象,替换模板文件中的${Name}、${id}中的值,如:

Map map = new HashMap();

map.put("project",

project);

map.put("name",

xr.changeToLower(className));

map.put("Name",

className);

map.put("Id",

xr.changeToUpper(idName));

map.put("id",

idName);

运行代码的时候,就可以生成相应的Java文件,并保存在项目的特定位置中!

3、测试:

package com.rongji.filecenter.test;

import com.rongji.filecenter.utils.TemplateUtil;

public class TestTemplate {

public static void main(String[] args) {

TemplateUtil tu = new

TemplateUtil();

tu.process("filecenter");

}

}

4、运行结果:

通过运行如上测试代码,生成一下文件:

《1》FcAppDao.java

package com.rongji.filecenter.dao;

import com.rongji.filecenter.persistence.FcApp;

public interface FcAppDao {

public FcApp getFcAppById(String fcApp);

public void saveFcApp(FcApp fcApp);

}

《二》FcAppDaoImpl

package com.rongji.filecenter.dao.impl;

import java.util.List;

import com.rongji.dfish.framework.FrameworkHelper;

import com.rongji.dfish.util.Utils;

import com.rongji.filecenter.dao.FcAppDao;

import com.rongji.filecenter.dao.BeansFactory;

import com.rongji.filecenter.persistence.FcApp;

public class FcAppDaoImpl implements FcAppDao {

private String tblName = "FcApp";

public void saveFcApp(FcApp fcApp) {

if (fcApp != null) {

String msgId

= fcApp.getAppId();

if

(Utils.isEmpty(msgId)) {

fcApp.setAppId((FrameworkHelper.getNewId(tblName,

"appId", "00000001")));

}

BeansFactory.getPubDao().saveObject(fcApp);

}

}

public FcApp getFcAppById(String appId)

{

if (Utils.isEmpty(appId))

return

null;

List

list = BeansFactory.getPubDao().getQueryList("from " + tblName + "

t WHERE t.id=?", appId);

if (list != null

&& list.size() > 0)

{

return

(FcApp) list.get(0);

}

return null;

}

}

其他生成文件略!

如果想增加其他功能模块,只需要修改模板文件,而不需要修改源代码,并且,可以移植到其他项目使用,为开发人员节省时间!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值