advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Reviews : Java Books : Hibernate: A Developer's Notebook :

Buy this book
Title: Hibernate: A Developer's Notebook
ISBN: 0596006969
US Price: $16.97
©2004 O'Reilly

Chapter 2. Introduction to Mapping

Now that we're in a position to work with Hibernate, it's worth pausing to reflect on why we wanted to in the first place, lest we remain lost in the details of installation and configuration. Object-oriented languages like Java provide a powerful and convenient abstraction for working with information at runtime in the form of objects that instantiate classes. These objects can link up with each other in a myriad of ways, and they can embody rules and behavior as well as the raw data they represent. But when the program ends, all the objects swiftly and silently vanish.

Writing a Mapping Document

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 (http://www.andromda.org/), turning them into Hibernate mappings.

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).

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.

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 Section 2.2.

TIP: 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.

NOTE 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.

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.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Google Hopes Chrome Will Help, Not Hurt Firefox
Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity

Code Around C#'s Using Statement to Release Unmanaged Resources
Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES