---
title: "Ant Task结合Hibernate Tools3.x快速开发"
author: "sqe_james"
date: "2009-03-30T11:19:13Z"
tags: ["Ant", "Hibernate", "MySQL", "XML", "freemarker"]
slug: "ant-task-hibernate-tools3-x"
draft: false
lastmod: "2009-03-30T11:22:09Z"
id: 357453
url: "https://janwer.iteye.com/blog/357453"
---

最近看Hibernate Reference 文档时，发现Hibernate Tools 3.x 这官方推荐的工具已经很强大了。由于之前开发如有用到Hibernate的 一般直接在Ant Task 中结合xdoclet2 来生成相关代码，在代码中有较好的标注才能生成质量过得去的代码，不是很方便。按开发流程我们一般需求分析时，会用PowerDesigner 一边讨论一边 开始建模，最后生成相关DataBase 的 Schema，由于PD的强大功能，用它来生成各种DB的Schema方便高效，主要以后变更DB时会很方便，代码质量也不错，当然它也能直接生成POJO看个人爱好了。

 

我的开发流程一般是PD CDM确定主要结构（建模分析）---&gt;生成PDM,根据需要作相应调整---&gt;相应DB的Schema---&gt;生成\*.hbm.xml,POJO和cfg.xml---&gt;根据情况微调后,开始开始DAO层---&gt;。。。。。。结合hibernate tools完成这一系列会相当轻松。但每个团队的实际情况不同，根据自身情况选择最佳方式。下面就Ant Task结合hibernatetool作个说明。

 

1\. Ant 构建环境

 先到 Hibernate 官网下载最新的 [Hibenate Tools](http://www.hibernate.org/6.html "Hibernate Tools Download") 解压后把 /plugins/org.hibernate.eclipse.x.x.x/lib/tools 目录下的 \*.jar copy 到 ANT 构建环境中。 e.g.

```
<path id="toolslib">
 <path location="lib/hibernate-tools.jar" />
 <path location="lib/hibernate3.jar" />
 <path location="lib/freemarker.jar" />
 <path location="${jdbc.driver.jar}" />
</path>
<taskdef name="hibernatetool" 
         classname="org.hibernate.tool.ant.HibernateToolTask" 
         classpathref="toolslib" />
```

 

2\. 建立全局ANT Task

其实一般用途的话，这个工具中就 &lt;hibernatetool&gt; 这个属性最主要。可以把它配置成全局的task 以便其它多处引用。具体格式如下：

```
<hibernatetool
  destdir="defaultDestinationDirectory"
  templatepath="defaultTemplatePath">
  <classpath ...>
  <property key="propertyName" value="value"/>
  <propertyset ...>
  (<configuration ...>|<annotationconfiguration ...>|
   <jpaconfiguration ...>|<jdbcconfiguration ...>)
  (<hbm2java>,<hbm2cfgxml>,<hbmtemplate>,...)  
</hibernatetool>
```

 你可以选其中的一项或多项。hibernatetool属性如下表：

**属性名称** **定义** **使用情况** destdir 生成文件的输入目录 Required templatepath 用户编辑模板的路径 Optional classpath 解析资源时的依赖环境 Optional,但通常是要求 property(and propertyset) 控制输出的属性设置，大部分与用户定义模板提供属性有关。 Optional

configuration

(annotationconfiguration, jpaconfiguration,

jdbcconfiguration)

必须为Hibernate元模型指定四个属性之一。 Required

hbm2java(hbm2cfgxml,

hbmtemplate, etc.)

指定一个或多个的输出方式 Required

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

下面举个例子：

```
<hibernatetool destdir="${build.dir}/generated">
 <classpath/>
 <configuration configurationfile="hibernate.cfg.xml"/>
 <!-- 用户模板 -->
 <hbmtemplate exporterclass="my.own.Exporter" filepattern="."/>
</hibernatetool>
```

注意： 以前的用户定义模板用Velocity ,现在开始使用Freemarker ，它提供给我们更好的异常和错误处理方式。

 

也可以简单地如下定义：

```
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" 
               classpathref="classpath" />
```

 

3\. 建立由DB到映射文件，POJO及配置文件的任务

由于有前面的全局定义，接下来的任务，既可以定义在一个target中，也可以分多个target来定义，看实际需求。先定义一下数据库属性文件hibernate.properties

```
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/vote?useUnicode=true&amp;characterEncoding=utf8
hibernate.connection.username=root
hibernate.connection.password=junwei
hibernate.dialect=org.hibernate.dialect.MySQLDialect
```

 接着就可以定义相关任务了：

```
<target name="hibernatecode">
  <!-- destdir属性可以在各输出属性中分别指定，这里是全局指定 -->
  <hibernatetool destdir="${build.dir}/generated">
    <!-- packagename表生成文件的存放包名 -->
    <jdbcconfiguration propertyfile="hibernate.properties" packagename="sqe.janier.model"/>
    <!-- 由DB导出hbm.xml文件 -->
    <hbm2hbmxml />
    <!-- 由hbm.xml文件生成POJO文件 -->
    <hbm2java jdk5="true" />
    <!-- 生成配置文件 -->
    <hbm2cfgxml ejb3="false" />
    <!-- 生成各POJO的相应DAO类，除非有定义自己的模板，否则这个功能别用 -->
    <hbm2dao />
    </hibernatetool>
</target>
```

 官方文档中还有其它很输出和定义形式，具体参看 [Hibernate Tools Reference Guide](http://docs.jboss.org/tools/3.0.0.CR1/en/hibernatetools/html_single/index.html#ant)

 

4\. hibernate 包中自带的Schema 生成工具

举个例子，schema 的生成，更新和验证ant task ，各参数说明见[Hibernate Reference Toolset Guide](http://www.hibernate.org/hib_docs/v3/reference/en-US/html/toolsetguide.html)

```
<target name="schemaexport">
  <taskdef name="schemaexport" 
                 classname="org.hibernate.tool.hbm2ddl.SchemaExportTask" 
                 classpathref="classpath" />
  <schemaexport properties="hibernate.properties" quiet="no" text="no" drop="no" 
        delimiter=";" output="schema-export.sql">
    <fileset dir="${src.dir}">
      <include name="**/*.hbm.xml" />
    </fileset>
  </schemaexport>
</target>

<target name="schemaupdate">
  <taskdef name="schemaupdate" 
                 classname="org.hibernate.tool.hbm2ddl.SchemaUpdateTask" 
                 classpathref="classpath" />
  <schemaupdate properties="hibernate.properties" quiet="no">
    <fileset dir="${src.dir}">
      <include name="**/*.hbm.xml" />
    </fileset>
  </schemaupdate>
</target>

<target name="schemavalidate">
  <taskdef name="schemavalidator" 
                 classname="org.hibernate.tool.hbm2ddl.SchemaValidatorTask"
                 classpathref="classpath" />
  <schemavalidator properties="hibernate.properties">
    <fileset dir="${src.dir}">
      <include name="**/*.hbm.xml" />
    </fileset>
  </schemavalidator>
</target>
```

 其实这些功能hibernate tools 都也具备的如hbm2ddl ，只是看各人喜欢，生成代码质量都不错。