Hibernate Class Generation Using hbm2java
Pages: 1, 2, 3, 4, 5, 6
hbm2java in Hibernate 3
The hbm2java tool has undergone a major overhaul in
Hibernate 3. In the new version of the Hibernate Tools (still in
alpha at the time of writing), the hbm2java task has been
integrated, among other similar tasks, into the
hibernatetool task. The Ant task will need to find the
following .jar files on the class path:
- hibernate-tools.jar
- velocity-1.4.jar
- velocity-tools-generic-1.4.jar
- jtidy-r8-21122004.jar
- hibernate3.jar
- JDBC drivers
Then the task is declared as follows:
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="maven.dependency.classpath"/>
Finally, you invoke the hbm2java task from within
the hibernatetool task, as follows:
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="maven.dependency.classpath"/>
<hibernatetool destdir="src/main/generated/src/java">
<configuration configurationfile="src/main/hibernate/hibernate.cfg.xml">
<fileset dir="src/main/hibernate">
<include name="**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2java />
</hibernatetool>
Note that the Hibernate 3 version of the tool, while very
promising, is still in an alpha version at the time of writing, so
it should be used with caution.
Customizing Generated Domain Classes
Now you know how to generate Java source code from the Hibernate mappings. What next?
To discuss some finer details, we will use a simple class model,
illustrated in Figures 2 and 3. The class model represents an
Employees database. Each employee is assigned to a country, and
speaks one or more languages. Each country also has a set of
international airports.

Figure 2. The UML class diagram for the demo application

Figure 3. The database schema used in the demo
application
Sometimes you may want to add domain logic into your domain classes. Indeed, for many people, the main disadvantage of generating the Java classes is that the domain classes become relatively passive; it is not easy to add business logic methods into the generated domain classes, which arguably makes them somewhat less "object-oriented." There is no one-size-fits-all solution to this problem, but a few possible approaches are described here.