Hibernate uses an XML document to track the mapping between Java classes and relational database tables. This mapping document is designed to be readable and hand-editable. You can also start by using graphical CASE tools (like Together, Rose, or Poseidon) to build UML diagrams representing your data model, and feed these into AndroMDA ( www.andromda.org/ ), turning them into Hibernate mappings.
Don't forget that Hibernate and its extensions let you work in other ways, starting with classes or data if you've got them.
We'll write one by hand, showing it's quite practical.
We're going to start by writing a mapping document for tracks , pieces of music that can be listened to individually or as part of an album or play list. To begin with, we'll keep track of the track's title, the path to the file containing the actual music, its playing time, the date on which it was added to the database, and the volume at which it should be played (in case the default volume isn't appropriate because it was recorded at a very different level than other music in the database).
2.1.1 Why do I care?
You might not have any need for a new system to keep track of your music, but the concepts and process involved in setting up this mapping will translate to the projects you actually want to tackle.
2.1.2 How do I do that?
Fire up your favorite text editor, and create the file Track.hbm.xml in the src/com/oreilly/hh directory you set up in the previous Chapter. (If you skipped that chapter, you'll need to go back and follow it, because this example relies on the project structure and tools we set up there.) Type in the mapping document as shown in Example 2-1. Or, if you'd rather avoid all that typing, download the code examples from this book's web site, and find the mapping file in the directory for Chapter 2.
Example 2-1. The mapping document for tracks, Track.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping 3 PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> 5 <hibernate-mapping> 6 7 <class name="com.oreilly.hh.Track" table="TRACK"> 8 <meta attribute="class-description"> 9 Represents a single playable track in the music database. 10 @author Jim Elliott (with help from Hibernate) 11 </meta> 12 13 <id name="id" type="int" column="TRACK_ID"> 14 <meta attribute="scope-set">protected</meta> 15 <generator class="native"/> 16 </id> 17 18 <property name="title" type="string" not-null="true"/> 19 20 <property name="filePath" type="string" not-null="true"/> 21 22 <property name="playTime" type="time"> 23 <meta attribute="field-description">Playing time</meta> 24 </property> 25 26 <property name="added" type="date"> 27 <meta attribute="field-description">When the track was created</meta> 28 </property> 29 30 <property name="volume" type="short"> 31 <meta attribute="field-description">How loud to play the track</meta> 32 </property> 33 34 </class> 35 </hibernate-mapping>
The first four lines are a required preamble to make this a valid XML document and announce that it conforms to the document type definition used by Hibernate for mappings. The actual mappings are inside the hibernate-mapping tag. Starting at line 7 we're defining a mapping for a single class, com.oreilly.hh.Track , and the name and package of this class are related to the name and location of the file we've created. This relationship isn't necessary; you can define mappings for any number of classes in a single mapping document, and name it and locate it anywhere you want, as long as you tell Hibernate how to find it. The advantage of following the convention of naming the mapping file after the class it maps, and placing it in the same place on the class path as that class, is that this allows Hibernate to automatically locate the mapping when you want to work with the class. This simplifies the configuration and use of Hibernate.
In the opening of the class tag on line 7, we have also specified that this class is stored in a database table named TRACK . The next tag, a meta tag (lines 8-11), doesn't directly affect the mapping. Instead, it provides additional information that can be used by different tools. In this case, by specifying an attribute value of 'class-description,' we are telling the Java code generation tool the JavaDoc text we want associated with the Track class. This is entirely optional, and you'll see the result of including it in the upcoming section, 'Generating Some Class.'
| || |
Although databases vary in terms of whether they keep track of the capitalization of table and column names , this book will use the convention of referring to these database entities in all-caps, to help clarify when something being discussed is a database column or table, as opposed to a persistent Java class or property.
The remainder of the mapping sets up the pieces of information we want to keep track of, as properties in the class and their associated columns in the database table. Even though we didn't mention it in the introduction to this example, each track is going to need an id . Following database best practices, we'll use a meaningless surrogate key (a value with no semantic meaning, serving only to identify a specific database row). In Hibernate, the key/id mapping is set up using an id tag (starting at line 13). We're choosing to use an int to store our id in the database column TRACK_ID , which will correspond to the property id in our Track object. This mapping contains another meta tag to communicate with the Java code generator, telling it that the set method for the id property should be protected ”there's no need for application code to go changing track IDs.
The generator tag on line 15 configures how Hibernate creates id values for new instances. (Note that it relates to normal O/R mapping operation, not to the Java code generator, which is often not even used; generator is more fundamental than the optional meta tags.) There are a number of different ID generation strategies to choose from, and you can even write your own. In this case, we're telling Hibernate to use whatever is most natural for the underlying database (we'll see later on how it learns what database we're using). In the case of HSQLDB, an identity column is used.
After the id, we just enumerate the various track properties we care about. The title (line 18) is a string, and it cannot be null. The filePath (line 20) has the same characteristics, while the remainder are allowed to be null: playTime (line 22) is a time , added (line 26) is a date , and volume (line 30) is a short . These last three properties use a new kind of meta attribute, 'field-description,' which specifies JavaDoc text for the individual properties, with some limitations in the current code generator.
You may be thinking there's a lot of dense information in this file. That's true, and as you'll see, it can be used to create a bunch of useful project resources.
2.1.3 What just happened ?
We took the abstract description of the information about music tracks that we wanted to represent in our Java code and database, and turned it into a rigorous specification in the format that Hibernate can read. Hopefully you'll agree that it's a pretty compact and readable representation of the information. Next we'll look at what Hibernate can actually do with it.
2.1.4 What about...
...Other data types, including nested classes and enumerations? Relationships between tables? Indices? Class hierarchies and polymorphism? Tables that contain rows we need to ignore? Hibernate can handle all these things, and we'll cover most of them in later examples. Appendix A lists the basic types that Hibernate supports 'out of the box.'