Hibernate Tools V4.3.X 生成中文註釋

 

在ECLIPSE MARS 2,經過Marketplace,安裝JBOSS TOOLS 4.3.0 Final,安裝的Hibernate Tools是 hibernate-tools-4.3.1.Final.jar,經過搜索,使用的路徑《eclipse-jee-mars-2-win32-x86_64\eclipse\configuration\org.eclipse.osgi\1089\0\.cp\lib》 html

同時也安裝有3.5.X,3.6.X,4.0.X幾個版本。使用Hibernate Tools生成entity和hbm.xml是,數據庫裏面的數據表和字段的註解沒法顯示Comment。 java

0x01 參考

Hibernate Tools生成註釋 git

http://www.blogjava.net/pauliz/archive/2009/11/13/302162.html github

《hibernate-tools使用心得》 sql

http://blog.sina.com.cn/s/blog_49baa8c001015kgt.html 數據庫

 

0x02 修改代碼

下載Hibernate Tools代碼,參考Hibernate Tools生成註釋》修改對應的代碼。 app

下載地址:https://github.com/hibernate/hibernate-tools eclipse

選擇4.3.x分支 函數

 

能夠經過GIT CLONE或者本身建個普通的JAVA工程,把代碼放上去,把依賴的JAR包放上去。 post

依賴的包,經過MAVEN BUILD一下就能夠到本地的倉庫了。

 

修改FreeMarker模板

 

PojoFields.ftl

 

<#-- // Fields -->

 

<#foreach field in pojo.getAllPropertiesIterator()>

<#if pojo.getMetaAttribAsBool(field, "gen-property", true)>   

/**

<#if pojo.hasMetaAttribute(field, "field-description")>

     ${pojo.getFieldJavaDoc(field, 0)}

</#if>

<#foreach column in field.columnIterator><#if column.comment?exists && column.comment?trim?length!=0>    

* Column comment: ${column.comment}.

</#if>

</#foreach>

*/

    ${pojo.getFieldModifiers(field)} ${pojo.getJavaTypeName(field, jdk5)} ${field.name}<#if pojo.hasFieldInitializor(field, jdk5)> = ${pojo.getFieldInitialization(field, jdk5)}</#if>;

</#if>

</#foreach>

 

PojoPropertyAccessors.ftl

 

<#-- // Property accessors -->

<#foreach property in pojo.getAllPropertiesIterator()>

<#if pojo.getMetaAttribAsBool(property, "gen-property", true)>

    /** 

<#if pojo.hasFieldJavaDoc(property)>   

     * ${pojo.getFieldJavaDoc(property, 4)}

</#if>

<#foreach column in property.columnIterator>

<#if column.comment?exists && column.comment?trim?length!=0>    

* getter: ${column.comment}.

</#if>

</#foreach>

*/

    <#include "GetPropertyAnnotation.ftl"/>

    ${pojo.getPropertyGetModifiers(property)} ${pojo.getJavaTypeName(property, jdk5)} ${pojo.getGetterSignature(property)}() {

        return this.${property.name};

    }

 

    /**

<#if pojo.hasFieldJavaDoc(property)>   

     * ${pojo.getFieldJavaDoc(property, 4)}

</#if>

<#foreach column in property.columnIterator>

<#if column.comment?exists && column.comment?trim?length!=0>    

* setter: ${column.comment}.

</#if>

</#foreach>

*/  

    ${pojo.getPropertySetModifiers(property)} void set${pojo.getPropertyName(property)}(${pojo.getJavaTypeName(property, jdk5)} ${property.name}) {

                   <#if pojo.hasMetaAttribute(property, "pre-cond")>

                            ${c2j.getMetaAsString(property, "pre-cond","\n")}

                   </#if> 

        this.${property.name} = ${property.name};

                   <#if pojo.hasMetaAttribute(property, "post-cond")>

                            ${c2j.getMetaAsString(property, "post-cond","\n")}

                   </#if> 

    }

</#if>

</#foreach>

 

PojoTypeDeclaration.ftl

 

/**

 * ${pojo.getClassJavaDoc(pojo.getDeclarationName() + " generated by hbm2java", 0)}

<#if clazz.table.comment?exists>

 * Entity: ${clazz.table.comment}

</#if>

 */

<#include "Ejb3TypeDeclaration.ftl"/>

${pojo.getClassModifiers()} ${pojo.getDeclarationType()} ${pojo.getDeclarationName()} ${pojo.getExtendsDeclaration()} ${pojo.getImplementsDeclaration()}

 

generalhbm.hbm.ftl

 

<?xml version="1.0"  encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

<hibernate-mapping>     

<!--

         Auto-generated mapping file from

         the hibernate.org cfg2hbm engine

         for General Global Setttings

-->

 

<#if c2h.isImportData(cfg)>

<#include "import.hbm.ftl">

</#if>

<#if c2h.isNamedQueries(cfg)>

<#include "query.hbm.ftl">

</#if>

<#if c2h.isNamedSQLQueries(cfg)>

<#include "sql-query.hbm.ftl">

</#if>

<#if c2h.isFilterDefinitions(cfg)>

<#include "filter-def.hbm.ftl">

</#if>

 

</hibernate-mapping>

 

hibernate-mapping.hbm.ftl

 

<?xml version="1.0"  encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

<!-- Generated ${date} by Hibernate Tools ${version} -->

<#if hmgs?exists && hmgs.hasNonDefaultSettings()>

<hibernate-mapping

<#if hmgs.hasDefaultPackage()>

 package="${hmgs.defaultPackage}"

 </#if>

<#if hmgs.hasSchemaName()>

 schema="${hmgs.schemaName}"

 </#if>

<#if hmgs.hasCatalogName()>

 catalog="${hmgs.catalogName}"

</#if>

<#if hmgs.hasNonDefaultCascade()>

 default-cascade="${hmgs.defaultCascade}"

 </#if>

<#if hmgs.hasNonDefaultAccess()>

 default-access="${hmgs.defaultAccess}"

 </#if>

<#if !hmgs.isDefaultLazy()>

         default-lazy="false"

         </#if>

<#if !hmgs.isAutoImport()>

         auto-import="false"

</#if>>

<#else>

<hibernate-mapping>

</#if>

 

<#include "persistentclass.hbm.ftl"/>

 

</hibernate-mapping>

 

如下根據上文參考文章進行修改:

TemplateProducer.java

jtidy.properties

MySQLMetaDataDialect.java

JDBCBinder.java

TemplateHelper.java

JDBCReaderFactory.java

TableIdentifier.java

 

0x03 解決hbm.xml生成中文亂碼問題

修改過的包,生成JAVAENTITY文件能夠顯示中文註解,可是生成的HBM.XML文件依然出現亂碼。緣由jtidy.properties好像設置了編碼格式沒生效。改造過的HIBERNATE TOOLS進行JTIDY格式化後,從新生成格式化後的HBM.XML出現亂碼。

org.hibernate.tool.hbm2x

XMLPrettyPrinter.java

 

修改一下函數爲:

 

   public static void prettyPrintFile(Tidy tidy, File inputFile,

         File outputFile, boolean silent) throws IOException {

      log.debug( "XMLPrettyPrinting " + inputFile.getAbsolutePath() );

 

      InputStream is;

      OutputStream os;

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      is = new BufferedInputStream( new FileInputStream( inputFile ) );

     

//    fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destination), "UTF-8"));

     

      outputFile.getParentFile().mkdirs();

      outputFile.createNewFile();

      os = new BufferedOutputStream(bos );

      tidy.setInputEncoding("utf-8");

      tidy.setOutputEncoding("utf-8");

     

      tidy.parse( is, os );

     

//    byte[] bs = bos.toByteArray();//亂碼致使亂碼。

//    byte[] bs = bos.toString("utf-8").getBytes();//依然亂碼

//    String tempWrite= new String(bs,"utf-8");//沒法解決亂碼

     

      String tempWrite=bos.toString("utf-8");

 

     

      try {

         is.close();

      }

      catch (IOException e1) {

         // ignore

      }

      try {

         os.flush();

         os.close();

      }

      catch (IOException e1) {

         // ignore

      }

 

      // generate output file

      if ( tidy.getParseErrors() == 0 ) {

//       BufferedOutputStream out = new BufferedOutputStream(

//              new FileOutputStream( outputFile ) );

//       InputStream in = new ByteArrayInputStream( bs );

        

         Writer fileWriter = null;

         fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));

        

         fileWriter.write(tempWrite);

        

         if(fileWriter!=null) {

            try {

                fileWriter.flush();

                fileWriter.close();

            }

            catch (IOException e) {

                log.warn("Exception while flushing/closing " + outputFile,e);

            }          

         }

        

         // Transfer bytes from in to out

//       byte[] buf = new byte[1024];

//       int len;

//       while ( (len = in.read( buf ) ) > 0 ) {

//          out.write( buf, 0, len );

//       }

//       in.close();

//       out.close();

      }

 

      if ( tidy.getParseErrors() > 0 ) {

         if(silent) {         

            log.warn("Tidy was unable to process file " + inputFile + ", " + tidy.getParseErrors() + " errors found." );

         } else {

            throw new ExporterException( "Tidy was unable to process file "

                   + inputFile + ", " + tidy.getParseErrors() + " errors found." );

         }

      } else {

         log.debug("XMLPrettyPrinting completed");

      }

   }

 

最後,替換生成的CLASS文件,jar -cvf hibernate-tools-4.3.1.Final.jar . 從新打包替換ECLIPSE目錄下的 hibernate-tools-4.3.1.Final.jar。

相關文章
相關標籤/搜索