Java Reference
In-Depth Information
Even for this trivial example there would be a further reduction in the amount of code
required in a real deployment—particularly in an application-server environment. For exam-
ple, the SessionFactory would normally be created elsewhere and made available to the
application as a Java Native Directory Interface ( JNDI) resource.
Note that the manual coding to populate the message object has not been eradicated—
rather, it has been moved into an external configuration file that isolates this implementation
detail from the main logic.
Some of the additional code in the Hibernate 3 example given in Listing 1-4 actually pro-
vides functionality (particularly transactionality and caching) beyond that of the JDBC example.
Mappings
As we have intimated, Hibernate needs something to tell it which tables relate to which
objects (this information is usually provided in an XML mapping file). While some tools
inflict vast, poorly documented XML configuration files on their users, Hibernate offers a
breath of fresh air—you create and associate a small, clear mapping file with each of the
POJOs that you wish to map into the database. You're permitted to use a single monolithic
configuration file if you prefer, but it's neither compulsory nor encouraged.
A document type definition (DTD) is provided for all of Hibernate's configuration files,
so with a good XML editor you should be able to take advantage of autocompletion and
autovalidation of the files as you create them. Java 5 annotations can be used to replace
them entirely.
Listing 1-5 shows the file mapping the Message POJO into the database.
Listing 1-5. The XML File That Maps the POJO to the Database
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Message" table="Message">
<id type="int" column="id">
<generator class="native"/>
</id>
<property name="message" column="message" type="string"/>
</class>
</hibernate-mapping>
It would be reasonable to ask if the complexity has simply been moved from the applica-
tion code into the XML mapping file. But, in fact, this isn't really the case for several reasons.
First, the XML file is much easier to edit than a complex population of a POJO from a
result set—and far more easily changed after the fact should your mappings into the database
change at a late stage of development.
Second, we have still done away with the complicated error handling that was required
with the JDBC approach. This is probably the weakest reason, however, since there are various
techniques to minimize this without resorting to Hibernate.
Search WWH ::




Custom Search