ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Hibernate Class Generation Using hbm2java

by John Ferguson Smart

Hibernate is a popular open source library for handling object/relational persistence and queries. In Hibernate, mapping between database tables and POJO ("plain old Java objects") classes is configured in a set of XML mapping files. hbm2java is a code generator that converts the mapping files into POJOs. It is part of the Hibernate Tools subproject and can be downloaded in the separate Hibernate Extensions package.

Several strategies exist for managing Hibernate mapping files, such as:

  • Writing everything by hand.
  • Putting xdoclet tags in your Java classes and generating the corresponding mapping file.
  • Generating a Hibernate mapping file and Java classes from the SQL schema.
  • Writing the Hibernate mapping files by hand, and generating Java classes and the SQL schema from the Hibernate mapping.
  • Writing the Hibernate mapping files by hand, based on a given SQL schema, and generating the Java classes using the hbm2java tool.

In this article, we will look at this last approach. Although such choices are often a matter of taste, this approach does has several advantages in many situations:

  • Hibernate mapping is centralized within the mapping files, rather than having the information dispersed among the Java source code, which can make maintenance easier. You also get a better control over the mapping, as in some cases, the XDoclet annotations do not support all of the functionality available in the Hibernate mapping schema.
  • The database schema can be maintained separately, rather than being generated from the classes or from the Hibernate mapping files. This allows the DBA, who may not be Java/Hibernate savvy, to have a better control over the nitty-gritty database details (indexes, tablespaces, table types, and so forth).

Generating Classes from the Mapping Files

In this approach, the Hibernate mapping files are king. All Hibernate mapping information is centralized in these files, meaning no annotations are used in the source code. All persistent classes are generated using the hbm2java tool. The classes cannot be modified afterwards.

This process is illustrated in Figure 1. First, you take the set of Hibernate mapping files. You may also need a hbm2java configuration file, generally called hbm2java.xml. Using these two entries, the hbm2java tool generates one or more Java classes for each Hibernate mapping file. The hbm2java configuration file can be useful for fine-tuning the class-generation process. (In Hibernate 3, this file is no longer used.)

Generating Java classes from the Hibernate mappings using hbm2java
Figure 1. Generating Java classes from the Hibernate mappings using hbm2java

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow