Despite their diverse set of outputs, the Hibernate tasks actually all work in the same way. The task is imported into Ant using the standard TaskDefelement. This makes the Hibernate tools libraries available to Ant itself, and allows you to select an appropriate element representing the Hibernate tools to use in your script.
<taskdef
name="htools"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="classpath.tools"/>
The Hibernate Tools JAR file must be made available to Ant on the classpath—our exam- ple uses a preexisting classpath declaration (referenced through its idof classpath.tools—
see the “Configuring the Classpath” subsection later in this section).
A standard Ant target is declared to contain the set of operations that you want to perform.
<target name="exportDDL" depends="compile">
…
</target>
Within the target with any other standard (or imported) Ant tasks, you can then include the element that you declared using the <taskdef>element. The other Hibernate task ele- ments are only applicable within this task element.
<target name="exportDDL" depends="compile">
<htools destdir="${sql}">
…
</htools>
</target>
This outermost task element accepts three attributes, as listed in Table B-1.
Table B-1.The Daughter Elements of the Hibernate Tools Task
Attribute Description
classpath The path to use when locating libraries and configuration files.
destDir The base directory (relative to the build script’s own base directory) into which any generated output will be written.
templatePath The path containing user-created template files (see the further discussion of templates in the “Templates” section later in the chapter.)
Within the declared Hibernate task, a number of additional standard elements can be created, consisting of a classpath declaration (an alternative to using the classpathattri- bute), a set of configuration elements, and a set of exporter elements.
The classpathelement and attribute are standard Ant features that allow you to bring in any necessary resources used by the Hibernate tasks.
The clever bit of the Hibernate Ant task lies in the configuration elements. Declaring a configuration task causes an appropriate configuration object to be built in memory. These in-memory configuration objects all extend the standard org.hibernate.cfg.Configuration class. The Configurationclass represents the mapping relationships between entities (com- bined with information from any configuration, properties, or reverse engineering files), and it is this information, the metamodel, that is then used to generate the various output files.
The provided configuration elements can conjure up a Configurationobject from the stan- dard mapping files, from the metadata information gathered over a JDBC connection, and from the annotations discussed in Chapter 6.
<target name="exportDDL" depends="compile">
<htools destdir="${sql}">
<annotationconfiguration
configurationfile="${src}/hibernate.cfg.xml"/>
…
</htools>
</target>
Within any given Hibernate Tools task, you can only have one configuration element con- figured—normally, you would not want to generate output from two distinct representations of the mapping information, so the single declaration is shared between the generation tasks enclosed within the toolset task elements. The following list describes the configuration tasks and the attributes of each:
• <configuration>: Mapping relationships are generated from conventional XML-based mapping files and information in a *.cfg.xmlor *.propertiesfile.
• configurationfile: The name of the XML configuration file being used.
• propertyfile: The name of the properties file being used.
• entityresolver: The name of the SAX EntityResolver to use when resolving “exter- nal” XML entities (rarely used).
• namingstrategy: A naming strategy to use (see Chapter 3) to establish table names from entity names.
• <annotationconfiguration>: Mapping relationships are generated from the EJB 3 and Hibernate 3 annotations in conjunction with a *.cfg.xmlor *.propertiesfile.
• Identical to <configuration>.
• <jdbcconfiguration>: Mapping relationships are generated from the schema metadata obtained over a JDBC connection. The connection details are configured from a prop- erties file.
• All those from <configuration>, plus the following:
• packagename: The name of the package that entities should belong to.
• reversestrategy: The fully qualified name of a class implementing the org.
hibernate.cfg.reveng.ReverseEngineeringStrategyinterface. This is the pro- grammatic equivalent of the reveng.xmlfile approach.
• revengfile: The name of a reverse engineering file to use when processing meta- data information. See the discussion later in this section.
• <ejb3configuration>: Mapping relationships are generated from the EJB 3 and Hiber- nate 3 annotations in conjunction with an EJB 3–compliant persistence.xmlfile.
• entityresolver: The name of the SAX EntityResolver to use when resolving “exter- nal” XML entities.
• namingstrategy: A naming strategy to use (see Chapter 3) to establish table names from entity names.
The <configuration>element also allows you to specify a standard Ant <fileset>of
*.hbm.xmlmapping files. If you use this in conjunction with a *.cfg.xmlconfiguration file, you must not permit any mapping resources to be duplicated, as this will result in duplicate import mapping exceptions.
Your choice of configuration element will be driven by the data sources that you have available to you. For example, if you have created your XML mapping files, you will want to use the standard configuration element, but if you have only a normalized database, you will want to generate the mapping information from this using the JDBC configuration (although you may well choose to create a reverse engineering file to control this).
Once you have correctly configured an annotation object, however, you can generate any of the other resources that you might need using one or more exporter elements. These are listed in Table B-2.
Table B-2.The Available Exporter Elements Element Description
<hbm2ddl> Generates tables from the metamodel
<hbm2cfgxml> Generates a *.cfg.xmlconfiguration file from the metamodel
<hbm2java> Generates entity POJOs from the metamodel
<hbm2hbmxml> Generates Hibernate *.hbm.xmlmapping files from the metamodel
Continued
Table B-2.Continued
Element Description
<hbm2doc> Generates HTML documentation for the database schema from the metamodel
<hbm2dao> Generates standard DAOs from the metamodel
<hbmtemplate> Generates arbitrary user-defined output from the metamodel
<query> Runs arbitrary HQL queries against the database using the mapping information in the metamodel
You may notice that the exporters available as Ant tasks correspond fairly closely to the exporters available in the Hibernate Code Generation tool—largely because they rely upon the same underlying implementations.
The two most commonly used tasks are <hbm2ddl>, which can generate a database schema directly from the *.hbm.xmlmapping files, and <hbm2hbmxml>, which, conversely, can generate mapping files directly from the database.
The <hbm2ddl>element generates DDL scripts from the metamodel. These can be written to a file—or, if the configuration object is provided with database connection details, they can be run directly against the database. Table B-3 shows the attributes that can be supplied.
Table B-3.The Attributes Available to the <hbm2ddl>Element
Property Default Description
create true If set to true, causes the generated DDL to include commands to create database objects. This allows to distinct tasks to be created:
one to drop all relevant database objects (using the dropattribute) and the other to create them.
console true If set to true, causes the generated DDL to be displayed on the console.
delimiter ; Specifies the delimiter to be used to separate DDL statements.
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task.
drop false If set to true, causes the generated DDL to include commands to drop preexisting database objects before it tries to create them. This may cause warning messages, depending upon the preexisting state of the database; and it of course has the potential to destroy existing data.
export true If set to true, causes the DDL to be run directly against the data- base (this has the potential to delete data—do not use carelessly).
format false If set to true, causes the generated DDL to be formatted using whitespace in a more readable fashion. We recommend using this option if you will be writing the DDL to a file.
haltonerror false If set to true, causes the script to halt if an error is encountered while generating the DDL (typically, this is used while exporting directly to the database to increase the visibility of any problems encountered while setting up the schema).
outputfilename Specifies the name of the file name that the generated DDL should be stored in. If left unset, the generated DDL will not be stored.
update false Indicates that the tool should attempt to generate the appropriate statements to bring the existing schema inline with the model. We don’t recommend using this option.
The task shown in Listing B-2, which completes the simple example that we’ve been building up in this section, creates a schema generation script from the annotation-based mappings referenced in the project’s hibernate.cfg.xmlfile.
Listing B-2.A Complete Hibernate Mapping Target
<target name="exportDDL" depends="compile">
<htools destdir="${sql}">
<annotationconfiguration
configurationfile="${src}/hibernate.cfg.xml"/>
<hbm2ddl
create="true"
drop="true"
format="true"
export="true"
outputfilename="${ant.project.name}.dll"/>
</htools>
</target>
The <hbm2cfgxml>element generates a Hibernate XML configuration file from the meta- model information. Table B-4 shows the attributes that can be supplied.
Table B-4.The Attributes Available to the <hbm2cfgxml>Element
Property Default Description
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task.
ejb3 false By default, causes entities to be mapped using <mapping
resource="..."/>entries in the configuration file. If set to true, the entities will be mapped using the <mapping class="..."/>approach to pick up EJB 3 annotations in the mapped classes. This setting does not cause a persistence.xmlfile to be generated!
Typically, the <hbm2cfgxml>element is used when the configuration task has been config- ured from a properties file—for example, when using <jdbcconfiguration>, you would typically start with a normalized database schema and a properties file containing the connection details, and use this exporter to create a hibernate.cfg.xmlfile containing both the connection details and the details of the mapped entities.
The <hbm2java>element generates the Java source code for POJOs for each of the entities held in the metamodel. Table B-5 shows the attributes that can be supplied.
Table B-5.The Attributes Available to the <hbm2java>Element
Property Default Description
destdir If set, overrides, for this exporter only, the destination directory speci- fied on the tools task
ejb3 false If set to true, causes the POJOs to be generated with EJB 3 annotations jdk5 false If set to true, causes the POJOs to be generated with Java 5 constructs
(generics, enumerations, etc.)
This exporter can be used to permit the mapping file–based creation of suitable classes, or to create classes from the database schema when <jdbcconfiguration>is used.
The <hbm2hbmxml>element generates the XML mapping files from the information con- tained in the metamodel. Table B-6 shows the attributes that can be supplied.
Table B-6.The Attributes Available to the <hbm2hbmxml>Element
Property Default Description
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task
This exporter is particularly terse because it only writes out the mapping information stored in the metamodel. This is all handled by the appropriate configuration element. The
<hbm2hbmxml>exporter just needs to know which path to write the XML files into. And that can be specified at the Hibernate tool level. A fairly typical invocation of this exporter is, in its entirety, the ridiculously simple <hbm2hbmxml/>.
The <hbm2doc>element generates HTML documentation of the schema and entities in a style similar to the familiar javadoc output. Table B-7 shows the attributes that can be supplied.
Table B-7.The Attributes Available to the <hbm2doc>Exporter Element
Property Default Description
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task
The <hbm2dao>element generates a set of basic DAO classes—one for each of the entities in the metadata. Table B-8 shows the attributes that can be supplied.
Table B-8.The Attributes Available to the <hbm2dao>Exporter Element
Property Default Description
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task
By default, these DAO classes will be named after your entity, suffixed with Home. The gen- erated DAOs provide a set of methods roughly corresponding to the methods available on the Sessioninterface, but strongly tied to the entity type. While the generated DAOs can provide a useful foundation for your own more specific DAOs, we generally find that they offer little value beyond that already offered from the standard Sessioninteractions.
■ Note Nothing in any of the exporters intrinsically stops you from generating “silly” combinations of output—
but this has its advantages; for example, it is possible to use an <annotationsconfiguration>configuration element with the <hbm2java>exporter to generate POJOs. While that might seem pointless, given that you have to start with POJOs to use an annotations-based configuration in the first place, it actually provides the useful ability to generate Java 1.4–compatible source code from annotated Java 5 class files!
In principle, the <query>element allows you to specify an arbitrary HQL query that will be run against the database using the configuration’s mapping information. Table B-9 shows the attributes that can be supplied.
Table B-9.The Properties Available to the <query>Exporter Element Property Default Description
destdir If set, overrides, for this exporter only, the destination directory specified on the tools task.
destfile If set, specifies the file into which the output of the queries will be writ- ten. If left unset, the query is carried out, but the output is not saved.
The HQL query itself is included as the body of the <query>element.
<query destdir="output" destfile="sql.log">
select n.owner from Notepad n
</query>
If you want to include multiple SQL queries in the task, you can include multiple nested
<hql>elements thus:
<query destdir="output" destfile="sql.log">
<hql>select n.owner from Notepad n</hql>
<hql>select n.owner from Note n</hql>
</query>