Chapter 11. Hibernate and Eclipse: Really Using the Hibernate Tools

Installing the Hibernate Tools in Eclipse

If you’re working with Eclipse as your Java development environment (as so many of us are these days), you can take far deeper advantage of the Hibernate Tools than we have been in the rest of the book (where we just used them to add Hibernate-related capabilities to our Ant builds).

How do I do that?

Before diving in, make sure you’re running a recent enough version of Eclipse. The current release of the Hibernate Tools requires at least Eclipse 3.3 and WTP 2.0. So here’s an excuse to upgrade if you’ve been putting it off.

The easiest way to install the Hibernate Tools into Eclipse is through Eclipse’s normal update site mechanism. Start by telling Eclipse where to find Hibernate Tools, by choosing the Find and Install option in the Software Update menu, as shown in Figure 11-1.

Updating features in Eclipse
Figure 11-1. Updating features in Eclipse

We want to install something completely new, rather than update an existing plug-in, so choose Search for new features to install, and click Next.

Eclipse doesn’t automatically know about the Hibernate Tools update site, so we need to explain where to find it. Click on New Remote Site, as shown in Figure 11-2.

Installing from a new Update Site in Eclipse
Figure 11-2. Installing from a new Update Site in Eclipse

Enter something descriptive like “Hibernate Tools” for the name of the new update site. As you’ll see later in Figure 11-4, Eclipse now wants us to specify the URL at which the update site can be found. We’ll have to do a little hunting to figure that out...

Switch to a web browser, open up the Hibernate web site at http://hibernate.org, and click on Hibernate Tools in the navigation menu on the lefthand side. (Or you can cut to the chase by opening http://tools.hibernate.org directly.) Once you’re there, you can read a bit about the tools, and follow various documentation links. We did that for a while, trying to figure out how to install the tools directly into Eclipse, and eventually noticed what we’d been missing: there’s an update site link right on the Tools page. Copy that URL to your clipboard, as shown in Figure 11-3 (you can right-click or Control-click on the link to get the menu to appear).

Getting the Hibernate Tools Update Site URL
Figure 11-3. Getting the Hibernate Tools Update Site URL

If you’re paying close attention, you may have noticed that the version of the Hibernate Tools mentioned on this page is newer than the beta 9 we’ve been using elsewhere in the book. Congratulations—you’ve spotted an example of how difficult it is to write about things that change as quickly as large open-source projects! At the time of this writing, the stable release is too new to be available through the Maven repository, so we’re leaving the rest of the book alone. The changes in the new release don’t affect the other chapters, in any case, but the latest version is necessary to work with the current release of Eclipse (3.3, also known as Europa, at the moment) and to enable some of the nicer features you’ll see in this chapter.

So, paste the URL for the update site into the New Update Site window in Eclipse. You should see something like Figure 11-4. Click OK to enable the new site.

Configuring a new Update Site in Eclipse
Figure 11-4. Configuring a new Update Site in Eclipse

As you can see from Figure 11-5, Eclipse makes the reasonable assumption that you want to use the update site you just configured, so click Finish to contact that site and see what can be installed from there.

New Update Site is ready to use
Figure 11-5. New Update Site is ready to use

The window that pops up (Figure 11-6) is simple and promising enough. All we need to do is check the single checkbox next to Hibernate Tools, and install away, right?

Installing the Hibernate Tools: we need to dig deeper
Figure 11-6. Installing the Hibernate Tools: we need to dig deeper

Unfortunately, as soon as we check the Hibernate Tools checkbox, we run into a snag. There’s an error message displayed at the top of the window, and the Next button is grayed out and unavailable to us.

What went wrong?

Eclipse won’t let us proceed, because the SeamTools feature (one of the 10 plug-ins that make up the Hibernate Tools group) requires another plug-in, org.eclipse.datatools.connectivity.feature, which is not installed by default. Unfortunately, we need to backtrack a bit. Click Cancel, then start over with the Find and Install menu option as you did at the beginning of this section. Once again, choose Search for new features to install, and click Next. This time, also enable the Europa Discovery Site, as shown in Figure 11-7, before clicking Finish.

Enabling the Eclipse Discovery Site
Figure 11-7. Enabling the Eclipse Discovery Site

Pick a mirror appropriate to your location from the list of choices and click OK (unless you’ve configured Eclipse to pick one automatically, which will save you this step). This time you’ll see two groups of plug-ins available, the Europa Discovery Site and the Hibernate Tools. Once again, choose the Hibernate Tools group for installation. As before, you’ll see an error at the top of the window, but this time we have the opportunity to fix that. One option would be to select the entire Europa Discovery Site group, but that would install a great deal more than is actually required, adding a great deal of unnecessary bloat to your Eclipse configuration.

So we want to figure out the minimal set of plug-ins we need from the Europa Discovery Site. Leaving the Hibernate Tools plug-in selected, expand the Europa Discovery Site group, but don’t try to select anything. Although it is possible to manually find and select the plug-in which is being reported as a requirement for the Hibernate Tools, this leads to a lot of tedious research and trial and error to figure out exactly which combination of plug-ins is required to get things working (we tried it, and once we found the plug-in that provided data tools connectivity feature mentioned in the first error, we found it had dependencies of its own, and wasn’t the only thing missing in the first place). Just as we were gritting our teeth in preparation for trying to write up a comprehensible explanation of how to select exactly what you need, we noticed the Select the Required button on the right. You can use it to automatically select the plug-ins you need. But our experimentation revealed that it only works if you first expand the disclosure triangle corresponding to the site from which the required plug-ins will be downloaded. It did nothing at all until we expanded the Europa Discovery site. Once that was done, clicking Select Required automatically selected just the plug-ins required to resolve the dependency errors. So, do that now, since you’ve got the Hibernate Tools selected and the Europa Discovery site expanded. You will end up with something like Figure 11-8, although the exact number of things to be installed will depend on what you might have already installed yourself in the past.

Required plug-ins selected
Figure 11-8. Required plug-ins selected

The important point is that we no longer have an error message blocking our ability to install the Hibernate Tools! So click Next to install this set of plug-ins. Accept the licenses that appear in the following dialog and click Next again. Another dialog window pops up showing you that there are a related set of optional features that you can also install. Since we don’t need them to work with the Hibernate Tools, just click Next in the Optional Features dialog to continue installing the precise set we requested.

The default installation locations (which will vary based on where Eclipse lives on your machine) are almost always fine, so unless you have special reasons to put them elsewhere, click Finish in the Installation dialog to go ahead and install the plug-ins.

The Update Manager will run for a while as the updates are downloaded. Eventually, a Feature Verification dialog will pop up. For each feature being installed, this will report whether or not it seems to be cryptographically signed by an organization that is trusted by the Eclipse project. Some of them will be; others (like the Hibernate Tools themselves) will lack valid signatures. This is common for third-party Eclipse plug-ins. Eclipse presents this situation as a warning, and wants to make sure you’re willing to install a plug-in under those circumstances. Since I have had confidence in the sites from which I’ve downloaded them, I’ve always proceeded with the installation, anyway. If you feel the same way (and, basically, if you want to use the Hibernate Tools, you’ll have to), click Install to proceed. (If you don’t want to be asked for each plug-in, click Install All to accept them in bulk). The Update Manager will proceed with the installation. When it finishes with everything, it will suggest that you restart Eclipse. Go ahead and click Yes, to be safe, and wait for Eclipse to come back.

Now what?

It’s immediately clear that Eclipse knows more about Hibernate than it used to. The icon for the Hibernate configuration file now gets a little Hibernate logo as part of it, and double-clicking on it or a mapping file opens a special editor that makes it easier to create and update such files, without seeing the underlying XML (Figure 11-9).

Hibernate configuration editor
Figure 11-9. Hibernate configuration editor

Note

This will certainly save me many trips to the reference documentation whether or not I’m working in source view!

Of course, you can still view the XML if you’re productive that way, by clicking on the Source tab at the bottom of the editor—and you’ll find that you now get completion assistance for the various Hibernate-related elements and their values when working with the source, as shown in Figure 11-10. This goes beyond the XML editor’s normal completion abilities for element names, which it can perform by analyzing the XML DTD, since the DTD says nothing about property names other than that they’re text.

Autocompletion of property names in the Hibernate configuration editor
Figure 11-10. Autocompletion of property names in the Hibernate configuration editor

Tip

You use the normal Eclipse completion key sequence, Control+Space, to bring up these pop ups.

The editor for mapping documents is shown in Figure 11-11. These two editors seem quite powerful and useful; it’s worth playing around with them for a while to get a feel for how they work and what they can do. By themselves they’d make a worthwhile addition to Eclipse for working with Hibernate.

Hibernate mapping editor
Figure 11-11. Hibernate mapping editor

To explore some of the other things you can do with the Hibernate Tools, they need to be activated for a project. If you’re starting a new project, you can choose to create a new Hibernate configuration file. If you’ve got an existing Hibernate project, as we did working up this chapter, you can skip that part and simply create a new Hibernate console.

Creating a Hibernate Console Configuration

With the project selected in the Project Explorer, choose FileNewOther, expand the Hibernate section that was added by the tools (Figure 11-12), and select Hibernate Console Configuration. (This is where you’ll also be able to choose to create a new configuration file, or XML mapping, as well as reverse engineering configuration files, which we won’t cover in this book.) Click Next to proceed with setting up the tools for your project.

New Eclipse wizards offered by the Hibernate Tools
Figure 11-12. New Eclipse wizards offered by the Hibernate Tools

Note

If you’re still using old-school properties files to configure Hibernate, you’d use the “Property file” field, found above the one we used in this example.

The Hibernate Console Configuration window appears (Figure 11-13). Tell the tools how to find your Hibernate configuration file by clicking on the corresponding Browse button, and locating the file within the project. (This is automatically set up for you when you use the configuration file wizard to create it in the first place, and the latest version of the tools seems to be smart enough to find it automatically in the project structure we’ve been using for the code examples in this book.)

Setting up a Hibernate Console configuration
Figure 11-13. Setting up a Hibernate Console configuration

The rest of the settings on this tab can be left as they are for most projects, but we do need to adjust the class path since we’re using the Maven Tasks for Ant to manage our dependencies, and the Hibernate Tasks won’t magically know how to find the database driver inside the Maven repository. So we need to click on the Classpath tab and tell it manually. On that tab we’ll click on the “Add External JARS” button, as shown in Figure 11-14.

Hibernate Console class path configuration
Figure 11-14. Hibernate Console class path configuration

Note

You can use HSQLDB in a shared mode as well, supporting multiple connections, but that is outside the scope of this book, and you’d still need to decide where and how to run the “server” JVM.

In the file selection dialog that results, we navigate inside our Maven repository (which can be found as described toward the end of “Setting Up a Project Hierarchy” in Chapter 1) to find the MySQL driver. In this case, under Mac OS X, the driver is found in ~/.m2/repository/mysql/mysql-connector-java/5.0.5/mysql-connector-java-5.0.5.jar. Building on the previous chapter, we’re continuing to work with MySQL. The Hibernate Tools are much more comfortable connecting to an external database; trying to work with an embedded in-memory database, the way we were using HSQLDB, isn’t a good idea, since the tools assume they are free to keep connections to the database open, which will force you to always quit Eclipse when you want to do other things with the database, like running the db task through ant to view its contents. A standalone database like MySQL, on the other hand, has no problems with multiple simultaneous connections.

After selecting the driver JAR, click Open (Figure 11-15).

Note

If you are using a proprietary database such as Oracle, you might need to download the JDBC Driver manually. Only freely distributable software is available in the Maven repository.

Locating the database driver JAR for the Hibernate Console configuration
Figure 11-15. Locating the database driver JAR for the Hibernate Console configuration

With the class path thus augmented (see Figure 11-16), we are ready to click Finish to establish our Hibernate Console configuration.

Hibernate Console class path configuration completed
Figure 11-16. Hibernate Console class path configuration completed

The Hibernate Tools ask us if we want to enable Hibernate support for our project (see Figure 11-17). Hurrah, that’s what we were after! We eagerly click OK.

Hibernate features ready to go
Figure 11-17. Hibernate features ready to go

More Editing Support

Now that we’ve got the Hibernate Tools enabled for our project, what kinds of things can we do? Well, now, when you’re editing a mapping file, the XML editor gains the ability to auto-complete table and column names for you (Figure 11-18). This explains why a project needs to be associated with a Hibernate Console configuration: the Hibernate Tools actually maintain a Hibernate session which can be used to inspect the database schema, and provide relevant assistance based on the actual project environment.

Autocompletion of column names in the Hibernate mapping editor
Figure 11-18. Autocompletion of column names in the Hibernate mapping editor

We’ve shown completion of column names in the TRACK table here, but you can complete table names as well (up in the class definition as well as in association definitions). Also, assuming you’ve already created the Java objects that will form your model, completion help is available for property names and class names, with JavaDoc support (as in Figure 11-19). Completion for property types is also always available, although that’s even easier to pick in the nonsource view, where it is a drop-down menu.

Warning

We did run into one “gotcha” in playing with database-driven completion. Even though SQL is usually case-insensitive when it comes to matching table and column names, the Hibernate Tools are not, and we couldn’t get completion to work properly until we noticed that our track table had been created in all lowercase, and our mapping document had been referring to it in uppercase. Fixing the mapping document to match the actual database capitalization got things working.

Autocompletion of property names in the Hibernate mapping editor
Figure 11-19. Autocompletion of property names in the Hibernate mapping editor

Another useful Eclipse feature is available here as well. The F3 key, which is used to navigate to the declaration of a variable, method, or class, works within the mapping editor to take you to the Java source for the class or property you’re mapping.

We were surprised and pleased to discover (Figure 11-20) that even our custom type mappings were available, at the bottom of the type completion menu, which did not seem to be the case in the GUI mapping editor.

Custom type mappings available for completion
Figure 11-20. Custom type mappings available for completion

But wait, there’s more!

These abilities mingle in with your normal Eclipse use, right in the Java perspective. But there are more tricks available once you open the Hibernate Console perspective, which you can do by clicking on the Open Perspective button in the toolbar and picking the Other choice, or choosing WindowOpen PerspectiveOther. Either approach yields the Open Perspective dialog shown in Figure 11-21. Choose Hibernate Console and click OK.

Opening the Hibernate Console perspective
Figure 11-21. Opening the Hibernate Console perspective

The Hibernate Console Perspective

The first thing to notice is the Hibernate Configurations view shown in Figure 11-22. We’ve expanded the “Hibernate ch 11” configuration we created at the start of this section, and dove down into some of the mappings, classes, and database schema entries it makes available for inspection. Notice the little graphical markers for identifiers, many-to-one, and one-to-many relationships. A wealth of information is available right in this view. We opened the drop-down menu to show that it offers access to several interesting features (and explains the purpose of the buttons to the left of the menu).

Hibernate Configurations view in the Hibernate Console perspective
Figure 11-22. Hibernate Configurations view in the Hibernate Console perspective

On the prosaic side, this menu offers us a way to edit our configuration, create new configurations for other Hibernate projects, and to refresh the view if we’ve changed things from outside Eclipse. More powerfully, the Run Schema Export option lets us achieve the same result for which we wrote the schema Ant task in Chapter 2, by simply selecting a configuration entry and running it.

The menu also gives us a hint about the purposes of the mysterious-looking buttons just to the left of it. Let’s explore what these do in more depth, starting with the HQL Editor choice. Figure 11-23 shows the view that opens upon picking that choice or clicking the button. It seems like a place we could explore HQL, but a quick attempt at table completion using Control+Space yields the error message, “Configuration not available nor open.” Although I think “or” would be more correct, we seem to need to associate the window with a Hibernate Console configuration. Fair enough—that makes sense—and although the interface is a bit distorted under Mac OS X, the menu at the top seems like a good candidate solution.

A blank, unconfigured HQL Editor view
Figure 11-23. A blank, unconfigured HQL Editor view

Sure enough, it’s a menu of configurations. Once we choose our Hibernate ch 11 configuration in the menu, the editor’s special powers come to life and completion works (see Figure 11-24). This is looking promising as a way to put together named queries for pasting into mapping documents, isn’t it? Let’s see what else it can do.

The HQL Editor view once connected to a Hibernate Console configuration
Figure 11-24. The HQL Editor view once connected to a Hibernate Console configuration

Tip

If you get the same error message about an unavailable configuration even after selecting it, this probably means the Hibernate Tools haven’t opened a SessionFactory for it yet. You can force this by right-clicking the configuration in the Hibernate Configurations view, and choosing Create SessionFactory (see Figure 11-25). Some other actions, like drilling down deeper into the Configurations, Session Factory, and Database tree nodes, seem to do the trick, too.

Explicitly opening a configuration’s SessionFactory
Figure 11-25. Explicitly opening a configuration’s SessionFactory

Completion help while authoring queries is certainly nice (it can complete property names, HQL keywords, and function names, too), but the real power of the tool comes from the fact that you can actually run queries and see their results—to convince yourself the query is right, your data is right, or just to learn more about HQL and your data model. Clicking on the big green Run HQL button at the top left of the editor view gives instant gratification, as in Figure 11-26.

The Run HQL button and its results
Figure 11-26. The Run HQL button and its results

Go ahead and try a bunch of queries. Add some projections, orderings, and aggregate functions—what a great opportunity to really learn about the query capabilities mentioned in Chapter 9! But, before moving on to the next editor type, there’s another trick or two to discover….

Tip

If you run queries against large tables, you may want to set a limit on the maximum number of results returned using the second menu at the top of the editor view. Since they all get loaded into memory, you might risk crashing Eclipse if you don’t. Our toy examples in this book are no trouble at all, of course.

The Properties view sitting below the Hibernate Configurations view has been behaving pretty normally so far, showing things like XML element attributes while we were editing mapping files, stuff you’ve probably seen in Eclipse before. Check out what happens when we click on one of the rows in our Hibernate Query Result view—Figure 11-27 shows the result of clicking on the William Orbit line in our Artist query results.

Browsing query results in the Properties view
Figure 11-27. Browsing query results in the Properties view

Note

What an awesome prototyping, exploration, learning, and debugging tool!

You can see all the Hibernate properties of the selected result object, and drill down through associations and collections by expanding the corresponding disclosure triangle. Again, try some experimentation on your own. (We probably didn’t even have to bother suggesting that….)

You may also have wondered what the Query Parameters view hovering to the right of the HQL editor is all about. (If you haven’t, maybe the view is not showing; open it by choosing WindowShow ViewOther, and picking Query Parameters from the Hibernate section.) This lets you play with queries containing named parameters. Figure 11-28 shows an example; we pasted in the tracksNoLongerThan named query from Chapter 3 to play with, then discovered that clicking the “:P+” button in the Query Parameters view populated the list with the (single) parameter in our query. We had to set the Type to time (that column is a drop-down), and with the help of the format cue below the list, entered a time in the Value column, clicked the green Run button at the top left of the query editor, and got the expected results in the Hibernate Query Result view at the bottom.

The Query Parameters interface for setting named parameters
Figure 11-28. The Query Parameters interface for setting named parameters

It’s hard to imagine a much easier interface for experimenting with HQL queries! And hardcore SQL geeks will be intrigued by this next trick (although you may well have already tried it for yourselves if you’re following along in Eclipse): the Hibernate Dynamic SQL Preview which you can see next to the query result tab in Figure 11-28; if it’s not showing in your own Eclipse, open it by choosing WindowShow ViewOther, and picking Hibernate Dynamic SQL Preview from the Hibernate section. Choosing this view reveals the actual SQL that is use to perform a HQL query we’ve entered in the query editor, as shown in Figure 11-29.

The Dynamic SQL Preview
Figure 11-29. The Dynamic SQL Preview

This view is very interesting because it really is dynamic, as the title suggests. If you have it open while you are editing a query in the HQL editor, you can watch the corresponding SQL evolving as you type. It is potentially quite instructive. For example, consider the very simple but natural HQL query in Figure 11-30, and the resulting SQL.

Seeing terse HQL as full SQL
Figure 11-30. Seeing terse HQL as full SQL

Tip

As one of our technical reviewers pointed out, this can also be a very valuable communication tool between Java developers who aren’t particularly SQL-savvy and DBAs who have no interest in hearing about HQL or JDBC.

Finally, the Criteria Editor view, accessed through the last unexplored button, is shown in Figure 11-31. It does what by now you probably expect. It provides a way for you to prototype Criteria queries, providing Java code completion (and the variable session is predefined to contain the Hibernate Console configuration’s session for use by the query).

The Hibernate Tools’ Criteria Editor
Figure 11-31. The Hibernate Tools’ Criteria Editor

Tip

If you find that completion isn’t working for you, remember to check that a valid Hibernate Console configuration is chosen in the menu next to the Run button, just like with the HQL Editor. Also, make sure Eclipse thinks the Criteria Editor view is selected (that it has a blue border). I sometimes managed to get it into a state where I was typing into it, but the query results view had the blue border, and none of the keyboard commands related to completion or editing worked the way they should.

What about…

…code generation features? These are available, too, and we didn’t even notice the most direct way of accessing them at first. They were already available before we enabled the tools for any specific project, although they couldn’t do much until we at least created one Hibernate Console configuration. A closer look at the Eclipse toolbar reveals a new menu offered by the Hibernate Tools (see Figure 11-32).

Code generation menu offered by the Hibernate Tools
Figure 11-32. Code generation menu offered by the Hibernate Tools

This new menu snuck in there so subtly, it took a while to see it. This menu is the “front door” to a graphical way of setting up and running the code generation features of the Hibernate Tools.

Code Generation

Let’s take a look at how we would replicate the codegen Ant target we created back in Chapter 2. To avoid sending you off on a page-flipping side trip, that target is reproduced as Example 11-1 here.

Example 11-1. Our code generation Ant task revisited
  <!-- Generate the java code for all mapping files in our source tree -->
  <target name="codegen" depends="usertypes"
          description="Generate Java source from the O/R mapping files">
    <hibernatetool destdir="${source.root}">
      <configuration configurationfile="${source.root}/hibernate.cfg.xml"/>
      <hbm2java jdk5="true"/>
    </hibernatetool>
  </target>

To reconstruct this within Eclipse, we started by choosing Open Hibernate Code Generation Dialog from the menu shown in Figure 11-32. The window that appears (Figure 11-33), like many of the Eclipse tools, provides a way of setting up a variety of named configurations you can run.

Preparing to create a new Hibernate code generation configuration
Figure 11-33. Preparing to create a new Hibernate code generation configuration

Tip

You seem to need to click on the Hibernate Code Generation label before the “New” button becomes active to create a new configuration.

Once we figured out how to activate it, we clicked on the “New” button (the one that looks like a little page with a plus sign at the top right corner) to set up a configuration to generate our data objects. That opens a configuration window with many options, some of which you can see in Figure 11-34.

Creating a Hibernate code generation configuration
Figure 11-34. Creating a Hibernate code generation configuration

Note

Of course, if you have more projects open in your Eclipse workspace, you’ll see more root choices in this browse dialog.

We assigned the configuration the name “Generate Ch 11 Model,” chose our Hibernate Console configuration, and browsed to the project’s src directory (see Figure 11-35), so the Main tab ended up looking like Figure 11-36.

Specifying the output directory for our generated code
Figure 11-35. Specifying the output directory for our generated code
Main code generation configuration to replicate our codegen Ant target
Figure 11-36. Main code generation configuration to replicate our codegen Ant target

We only need to worry about the Name and the top two choices in the Main tab, since we’re not trying to do fancy reverse-engineering based on existing data. (That’s a powerful feature you may want to explore on your own someday, when a big legacy schema lands on your lap that you need to make available in Java.) So we’re ready to move on to the Exporters tab. Clicking on that reveals the interface shown in Figure 11-37, once we’ve filled it in to reproduce the behavior of our Ant target.

Exporters configuration to replicate our codegen Ant target
Figure 11-37. Exporters configuration to replicate our codegen Ant target

We checked Use Java 5 syntax, the graphical equivalent of the jdk5=true attribute setting in the Ant task, and then chose the Domain code (.java) exporter. Notice that although we’re not using them here, there are a bunch of other generators available to us, for creating mapping files, the overall Hibernate configuration file, and even some web documentation of the database schema. Also, you can create some data access objects (DAO code) to make it easier to load and manipulate your model objects in a standardized, convenient way. Although beyond the scope of this book, these are all options you might want to explore on your own, or at least keep in the back of your mind for when they might come in handy.

Note

Which kind of defeats the purpose of offering a GUI…. At least they cover the common cases.

Tip

In case you’re wondering about the purpose of the Properties section at the bottom of the tab, it’s basically a cop-out to let you set parameters for each of the exporters that have not (yet?) been exposed through a graphical interface. Clicking on any of the exporters (the name, not the checkbox) shows any properties that have been manually set for that generator, and activates the Add and Remove buttons so you can edit them. Refer to the documentation of the generator to find out what properties are available, and what they do.

For the purposes of our current task, to reproduce what we previously did in our build.xml file, these are the correct settings. In fact, that’s all we’d really need to set up. While we’re in here, though, it’s worth looking at some Eclipse-specific options, too. The Refresh tab (see Figure 11-38) lets you control which Eclipse resources are automatically refreshed after running the exporters.

Refresh options for code generation
Figure 11-38. Refresh options for code generation

We chose to turn on refreshing, but just for the project into which we’re generating code. That seems appropriate for what we’re doing.

Finally, the default settings on the Common tab seemed fine, so we left them alone, and hit Apply.

Our configuration appeared in the list on the left (see Figure 11-39). At this point we can either run it by selecting it there and clicking the Run button (seen at the bottom right in Figure 11-34) or, if we think we’ll be running it often, we can set it up as a favorite in the toolbar menu so it appears right at the top of that menu. For now, we’ll just test it by running it from this dialog by selecting it and clicking Run.

Our code generation configuration is ready to be run
Figure 11-39. Our code generation configuration is ready to be run

Running it doesn’t cause anything flashy to happen, although the status bar at the bottom right of the Eclipse window briefly shows background activity (we left the Launch in background setting checked in the Common configuration, so that’s what we’d expect). To see if it really did anything, we can pull up one of the generated classes, such as Album.java, and take a look. The code in Example 11-2 shows the beginning of the Album source generated by the Hibernate Tools.

Example 11-2. Start of the Album source generated by the Hibernate Tools in Eclipse
package com.oreilly.hh.data;

// Generated Jan 5, 2008 6:36:04 PM by Hibernate Tools 3.2.0.CR1

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *       Represents an album in the music database, an organized list of tracks.
 *       @author Jim Elliott (with help from Hibernate)
 *     
 */
public class Album implements java.io.Serializable {

    private int id;

    private String title;

    private Integer numDiscs;

    private Set<Artist> artists = new HashSet<Artist>(0);
...

Both the time stamp and the tools version number tell us that this class has been newly generated. (Recall that we’re using version 3.2.0.b9 from Maven for the Ant tasks—who knew the delay getting the latest version into Maven would have a side benefit?) Other than that, the results look just like what we obtained from Ant. Not too exciting, perhaps, but actually just what we’d like to see.

So where, does this leave us? Having tools like this built into Eclipse can be huge time savers during the design and exploration phases of a project. Being able to put together queries—with schema-aware completion assistance, property browsing and real-time SQL display—is a great way to develop an understanding of the data and the model objects. It’s certainly much faster and more convenient than throwing together standalone example classes like our various query tests earlier in the book, then compiling, running, and tweaking them. You can try many more variations much more quickly, and with none of the tedious boilerplate (what little is left when using Hibernate, anyway) needed to get the environment set up.

Mapping Diagrams

For most of the time this book was being written, the Hibernate Tools were in beta, and this last feature was disabled. Luckily, right before we went to press, version 3.2 was finally released, with mapping diagrams available. A graphical view of the object and data models can be a great aid to understanding, and now you can produce these right inside Eclipse. To create one, choose a mapped class in the Hibernate Configurations view and bring up its contextual menu (right-click or Control-click on the element, as shown in Figure 11-40), and choose Open Mapping Diagram.

Opening a mapped object’s model diagram
Figure 11-40. Opening a mapped object’s model diagram

This produces a new view like the one in Figure 11-41. We’ve chosen a simple class here so the diagram fits on the page, but with a big screen you can view and scroll around through a complex set of associations in a very informative way. You can drag elements of the diagram around if you don’t like the way it was laid out, and you can use contextual menus within the diagram to open source files and mapping documents for elements that interest you.

Mapping diagram for the Artist class
Figure 11-41. Mapping diagram for the Artist class

Obviously, schema-aware XML and query editing, with GUI options for building mappings and Hibernate configurations, are incredibly useful capabilities—they augment one of the main benefits of using Eclipse in the first place. Diagrams to help visualize and understand the data model are icing on the cake. And, given the ability to dynamically interact with the Hibernate session, generate code with a button click, and run queries right in the IDE, it’s possible to get quite far without even setting up an Ant build file. If you’re thinking along those lines, and interested in getting rid of the clumsy requirement to manually add Maven resources to the class path, the next chapter will be right up your alley.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset