参考文章 http://www.blogjava.net/pauliz/archive/2009/11/13/302162.html
经实际操作总结如下
☆适用于Eclipse4.4及以下版本;
☆更高版本未测试,估计可行;
☆ Eclipse4.4需要修改两个目录下的文件;
☆本文以 hibernate-tools-3.4.0.CR2.jar为例
1. 安装Hibernate Tools插件
2. 解压文件--- hibernate-tools-3.4.0.CR2.jar
X:\Eclipse\plugins\org.hibernate.eclipse.libs_3.7.1.Final-v20140303-0022-B124\lib\tools\hibernate-tools-3.4.0.CR2.jar
或
X:\Eclipse \plugins\org.hibernate.eclipse.libs_4.0.1.Final-v20150324-2307-B95\lib\tools\hibernate-tools-3.4.0.CR2.jar
3. 修改文件
3.1 修改hibernate-tools-3.4.0.CR2\pojo\
PojoTypeDeclaration.ftl
<#--实体类的注释--> /*************************************************************************************** * @Package ${pojo.getQualifiedDeclarationName()} * @author Admin * @since ${date} ***************************************************************************************/ <#include "Ejb3TypeDeclaration.ftl"/> ${pojo.getClassModifiers()} ${pojo.getDeclarationType()} ${pojo.getDeclarationName()} ${pojo.getExtendsDeclaration()} ${pojo.getImplementsDeclaration()} |
PojoFields.ftl
<#-- //实体类的字段 Fields --> <#foreach field in pojo.getAllPropertiesIterator()> <#if pojo.getMetaAttribAsBool(field, "gen-property", true)> <#--代码格式1 //增加金额 private BigDecimal addZje; --> <#--
<#foreach column in field.columnIterator> <#if column.comment?exists && column.comment?trim?length!=0> //${column.comment} </#if> </#foreach>
--> <#--代码格式2 private BigDecimal addZje; //增加金额 -->
${pojo.getFieldModifiers(field)} ${pojo.getJavaTypeName(field, jdk5)} ${field.name} <#if pojo.hasFieldInitializor(field, jdk5)> ${pojo.getFieldInitialization(field, jdk5)} </#if>;<#foreach column in field.columnIterator><#if column.comment?exists && column.comment?trim?length!=0>//${column.comment}</#if></#foreach> </#if> </#foreach> |
PojoPropertyAccessors.ftl
<#-- //实体类的get/set Property accessors --> <#--注释格式1 /**ToGet: comment*/ /** ${column.comment} */ --> <#--代码格式2 //ToGet: comment //ToGet: ${column.comment} -->
<#foreach property in pojo.getAllPropertiesIterator()> <#if pojo.getMetaAttribAsBool(property, "gen-property", true)>
<#--GET方法--> <#foreach column in property.columnIterator> <#if column.comment?exists && column.comment?trim?length!=0> //ToGet: ${column.comment} </#if> </#foreach> <#include "GetPropertyAnnotation.ftl"/> ${pojo.getPropertyGetModifiers(property)} ${pojo.getJavaTypeName(property, jdk5)} ${pojo.getGetterSignature(property)}() { return this.${property.name}; }
<#--SET方法--> <#foreach column in property.columnIterator> <#if column.comment?exists && column.comment?trim?length!=0> //ToSet: ${column.comment} </#if> </#foreach> ${pojo.getPropertySetModifiers(property)} void set${pojo.getPropertyName(property)} (${pojo.getJavaTypeName(property, jdk5)} ${property.name}) { this.${property.name} = ${property.name}; }
</#if> </#foreach> |
Pojo.ftl
${pojo.getPackageDeclaration()} <#--// Generated ${date} by Hibernate Tools ${version} -->
<#assign classbody> <#include "PojoTypeDeclaration.ftl"/> {
<#if !pojo.isInterface()> <#include "PojoFields.ftl"/>
<#include "PojoConstructors.ftl"/>
<#include "PojoPropertyAccessors.ftl"/>
<#include "PojoToString.ftl"/>
<#include "PojoEqualsHashcode.ftl"/>
<#else> <#include "PojoInterfacePropertyAccessors.ftl"/>
</#if> <#include "PojoExtraClassCode.ftl"/>
} </#assign>
${pojo.generateImports()} ${classbody}
|
3.2修改hibernate-tools-3.4.0.CR2\dao\
daohome.ftl
<#--DAO 类 --> ${pojo.getPackageDeclaration()} <#-- // Generated ${date} by Hibernate Tools ${version} -->
<#assign classbody> <#assign declarationName = pojo.importType(pojo.getDeclarationName())> /*************************************************************************************** * @Package ${pojo.getQualifiedDeclarationName()} * @author Admin * @since ${date} ***************************************************************************************/ <#if ejb3> @${pojo.importType("javax.ejb.Stateless")} </#if> <#-- 默认开始 public class ${declarationName}Helper {
private static final ${pojo.importType("org.apache.commons.logging.Log")} log = ${pojo.importType("org.apache.commons.logging.LogFactory")}.getLog(${pojo.getDeclarationName()}Helper.class);
<#if ejb3> @${pojo.importType("javax.persistence.PersistenceContext")} private ${pojo.importType("javax.persistence.EntityManager")} entityManager;
public void persist(${declarationName} transientInstance) { log.debug("persisting ${declarationName} instance"); try { entityManager.persist(transientInstance); log.debug("persist successful"); }catch (RuntimeException re) { log.error("persist failed", re); throw re; } }
public void remove(${declarationName} persistentInstance) { log.debug("removing ${declarationName} instance"); try { entityManager.remove(persistentInstance); log.debug("remove successful"); }catch (RuntimeException re) { log.error("remove failed", re); throw re; } }
public ${declarationName} merge(${declarationName} detachedInstance) { log.debug("merging ${declarationName} instance"); try { ${declarationName} result = entityManager.merge(detachedInstance); log.debug("merge successful"); return result; }catch (RuntimeException re) { log.error("merge failed", re); throw re; } }
<#if clazz.identifierProperty?has_content> public ${declarationName} findById( ${pojo.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { log.debug("getting ${declarationName} instance with id: " + id); try { ${declarationName} instance = entityManager.find(${pojo.getDeclarationName()}.class, id); log.debug("get successful"); return instance; }catch (RuntimeException re) { log.error("get failed", re); throw re; } } </#if> <#else> private final ${pojo.importType("org.hibernate.SessionFactory")} sessionFactory = getSessionFactory();
protected ${pojo.importType("org.hibernate.SessionFactory")} getSessionFactory() { try { return (${pojo.importType("org.hibernate.SessionFactory")}) new ${pojo.importType("javax.naming.InitialContext")}().lookup("${sessionFactoryName}"); }catch (Exception e) { log.error("Could not locate SessionFactory in JNDI", e); throw new IllegalStateException("Could not locate SessionFactory in JNDI"); } }
public void persist(${declarationName} transientInstance) { log.debug("persisting ${declarationName} instance"); try { sessionFactory.getCurrentSession().persist(transientInstance); log.debug("persist successful"); }catch (RuntimeException re) { log.error("persist failed", re); throw re; } }
public void attachDirty(${declarationName} instance) { log.debug("attaching dirty ${declarationName} instance"); try { sessionFactory.getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); }catch (RuntimeException re) { log.error("attach failed", re); throw re; } }
public void attachClean(${declarationName} instance) { log.debug("attaching clean ${declarationName} instance"); try { sessionFactory.getCurrentSession().lock(instance, ${pojo.importType("org.hibernate.LockMode")}.NONE); log.debug("attach successful"); }catch (RuntimeException re) { log.error("attach failed", re); throw re; } }
public void delete(${declarationName} persistentInstance) { log.debug("deleting ${declarationName} instance"); try { sessionFactory.getCurrentSession().delete(persistentInstance); log.debug("delete successful"); }catch (RuntimeException re) { log.error("delete failed", re); throw re; } }
public ${declarationName} merge(${declarationName} detachedInstance) { log.debug("merging ${declarationName} instance"); try { ${declarationName} result = (${declarationName}) sessionFactory.getCurrentSession() .merge(detachedInstance); log.debug("merge successful"); return result; }catch (RuntimeException re) { log.error("merge failed", re); throw re; } }
<#if clazz.identifierProperty?has_content> public ${declarationName} findById( ${c2j.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { log.debug("getting ${declarationName} instance with id: " + id); try { ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession() .get("${clazz.entityName}", id); if (instance==null) { log.debug("get successful, no instance found"); }else { log.debug("get successful, instance found"); } return instance; }catch (RuntimeException re) { log.error("get failed", re); throw re; } } </#if>
<#if clazz.hasNaturalId()> public ${declarationName} findByNaturalId(${c2j.asNaturalIdParameterList(clazz)}) { log.debug("getting ${declarationName} instance by natural id"); try { ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession().createCriteria("${clazz.entityName}") <#if jdk5> .add( ${pojo.staticImport("org.hibernate.criterion.Restrictions", "naturalId")}() <#else> .add( ${pojo.importType("org.hibernate.criterion.Restrictions")}.naturalId() </#if> <#foreach property in pojo.getAllPropertiesIterator()> <#if property.isNaturalIdentifier()> .set("${property.name}", ${property.name}) </#if> </#foreach> ) .uniqueResult(); if (instance==null) { log.debug("get successful, no instance found"); }else { log.debug("get successful, instance found"); } return instance; }catch (RuntimeException re) { log.error("query failed", re); throw re; } } </#if> <#if jdk5> public ${pojo.importType("java.util.List")}<${declarationName}> findByExample(${declarationName} instance) { <#else> public ${pojo.importType("java.util.List")} findByExample(${declarationName} instance) { </#if> log.debug("finding ${declarationName} instance by example"); try { <#if jdk5> ${pojo.importType("java.util.List")}<${declarationName}> results = (List<${declarationName}>) sessionFactory.getCurrentSession() <#else> ${pojo.importType("java.util.List")} results = sessionFactory.getCurrentSession() </#if> .createCriteria("${clazz.entityName}") <#if jdk5> .add( ${pojo.staticImport("org.hibernate.criterion.Example", "create")}(instance) ) <#else> .add(${pojo.importType("org.hibernate.criterion.Example")}.create(instance)) </#if> .list(); log.debug("find by example successful, result size: " + results.size()); return results; }catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } <#foreach queryName in cfg.namedQueries.keySet()> <#if queryName.startsWith(clazz.entityName + ".")> <#assign methname = c2j.unqualify(queryName)> <#assign params = cfg.namedQueries.get(queryName).parameterTypes><#assign argList = c2j.asFinderArgumentList(params, pojo)> <#if jdk5 && methname.startsWith("find")> public ${pojo.importType("java.util.List")}<${declarationName}> ${methname}(${argList}) { <#elseif methname.startsWith("count")> public int ${methname}(${argList}) { <#else> public ${pojo.importType("java.util.List")} ${methname}(${argList}) { </#if> ${pojo.importType("org.hibernate.Query")} query = sessionFactory.getCurrentSession() .getNamedQuery("${queryName}"); <#foreach param in params.keySet()> <#if param.equals("maxResults")> query.setMaxResults(maxResults); <#elseif param.equals("firstResult")> query.setFirstResult(firstResult); <#else> query.setParameter("${param}", ${param}); </#if> </#foreach> <#if jdk5 && methname.startsWith("find")> return (List<${declarationName}>) query.list(); <#elseif methname.startsWith("count")> return ( (Integer) query.uniqueResult() ).intValue(); <#else> return query.list(); </#if> } </#if> </#foreach> </#if> }
默认结束-->
<#--自定义--> public class ${declarationName}Helper { public static ObjManager manger${declarationName} = ObjTools.GetManger( ${declarationName}.class );
//Get Object By String_ID public static ${declarationName} findById( String id ) { if (manger${declarationName}.findById(id) == null ) { return null; } else { return ( ${declarationName} ) manger${declarationName}.findById( id ); } }
//Get Object By long_ID public static ${declarationName} findById( long id ) { if (manger${declarationName}.findById(id) == null ) { return null; } else { return ( ${declarationName} ) manger${declarationName}.findById( id ); } }
}
</#assign>
${pojo.generateImports()} ${classbody} |
3.3 修改 hibernate-tools-3.4.0.CR2\org\hibernate\tool\hbm2x\
jtidy.properties追加
indent=auto indent-spaces=4 #indent-attributes=yes wrap=180 markup=yes clean=yes output-xml=yes input-xml=yes show-warnings=yes trim-empty-elements=yes input-encoding=UTF-8 output-encoding=UTF-8 |
TemplateProducer.class (需要自己先搭建环境再修改)
·创建JAVA项目
·引入2个jar包 hibernate-tools-3.4.0.CR2.jar org.apache.commons.logging_xxxxx.jar
·反编译.class \hibernate-tools-3.4.0.CR2\org\hibernate\tool\hbm2x\TemplateProducer.class
·创建javal类 TemplateProducer.java
package org.hibernate.tool.hbm2x;
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
public class TemplateProducer { private static final Log log = LogFactory.getLog(TemplateProducer.class); private final TemplateHelper th; private ArtifactCollector ac;
public TemplateProducer(TemplateHelper th, ArtifactCollector ac) { this.th = th; this.ac = ac; }
public void produce(Map additionalContext, String templateName, File destination, String identifier, String fileType, String rootContext) { String tempResult = produceToString(additionalContext, templateName, rootContext); if (tempResult.trim().length() == 0) { log.warn("Generated output is empty. Skipped creation for file " + destination); return; }
//FileWriter fileWriter = null; Writer fileWriter = null; try { this.th.ensureExistence(destination);
this.ac.addFile(destination, fileType); log.debug("Writing " + identifier + " to " + destination.getAbsolutePath());
//fileWriter = new FileWriter(destination); FileOutputStream ss = new FileOutputStream(destination); Writer gg = new OutputStreamWriter(ss, "UTF-8"); fileWriter = new BufferedWriter(gg);
fileWriter.write(tempResult);return; } catch (Exception e) { throw new ExporterException("Error while writing result to file", e); } finally { if (fileWriter != null) { try { fileWriter.flush(); fileWriter.close(); } catch (IOException e) { log.warn("Exception while flushing/closing " + destination, e); } } } }
private String produceToString(Map additionalContext, String templateName, String rootContext) { Map contextForFirstPass = additionalContext; putInContext(this.th, contextForFirstPass); StringWriter tempWriter = new StringWriter(); BufferedWriter bw = new BufferedWriter(tempWriter);
this.th.processTemplate(templateName, bw, rootContext); removeFromContext(this.th, contextForFirstPass); try { bw.flush(); } catch (IOException e) { throw new RuntimeException("Error while flushing to string", e); } return tempWriter.toString(); }
private void removeFromContext(TemplateHelper templateHelper, Map context) { Iterator iterator = context.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry)iterator.next(); templateHelper.removeFromContext((String)element.getKey(), element.getValue()); } }
private void putInContext(TemplateHelper templateHelper, Map context) { Iterator iterator = context.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry)iterator.next(); templateHelper.putInContext((String)element.getKey(), element.getValue()); } }
public void produce(Map additionalContext, String templateName, File outputFile, String identifier) { String fileType = outputFile.getName(); fileType = fileType.substring(fileType.indexOf('.') + 1); produce(additionalContext, templateName, outputFile, identifier, fileType, null); }
public void produce(Map additionalContext, String templateName, File outputFile, String identifier, String rootContext) { String fileType = outputFile.getName(); fileType = fileType.substring(fileType.indexOf('.') + 1); produce(additionalContext, templateName, outputFile, identifier, fileType, rootContext); } } |
4. 将以上修改的文件和新的.class文件替换到 hibernate-tools-3.4.0.CR2.jar 中
x:\eclipse\plugins\org.hibernate.eclipse.libs_3.7.1.Final-v20140303-0022-B124\lib\tools\hibernate-tools-3.4.0.CR2.jar
x:\eclipse\plugins\org.hibernate.eclipse.libs_4.0.1.Final-v20150324-2307-B95\lib\tools\hibernate-tools-3.4.0.CR2.jar