·使用MyEclipse开发Struts框架的Hello World!(录像1)
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·AWT GUI 设计笔记(二)


作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

Hibernate / Spring / Middlegen / XDoclet Tutorial v1.5

Part 1 in the Hibernate tutorial series

Before we begin

What this tutorial covers

This tutorial is built to help java developers get Hibernate, Spring, Middlegen and XDoclet up an running in a timely fashion.  When I first began learning Hibernate, Spring, Middlegen, and XDoclet, I was overwhelmed by how large and involved each package was.  Literally, there are thousands of files to deal with, vast amounts of jars to wade through, and so many different xml files that it's hard to know where to start. There are several excellent tutorials available online and they all were useful in someway to me, but none of them pandered to my way of learning, by example.  In response, I've attempted to compile them into a single tutorial, allowing developers like myself to get up to speed on these great technologies faster.  In essence, this tutorial is a "shortest" path example to getting all of these wonderful technologies working. Once you've completed this tutorial you should have a development process for integrating Hibernate, Spring, Middlegen, and XDoclet into your future projects.

What this tutorial doesn't cover

This tutorial won't review how Hibernate, Spring, Middlegen, or XDoclet work.  Additionally, this tutorial won't review the files I provide in the This may seem odd at first, but the documentation I've provided in the files does a great job of explaining them. If you find the documentation lacking and you have any questions please feel free to email me using the email address I've provided in the resource section, I'm always glad to help. Additionally, I can be contact on the under the handle TdC_VgA.

Downloading / Installing optional software

Install Command Prompt Here

Download: CmdHere.reg.txt
Install: Save CmdHere.reg.txt
          Rename CmdHere.reg.txt to cmdhere.reg
          Right click on cmdhere.reg -> Merge

Install Eclipse
Extract file to c:\java\eclipse (you can use any directory you like, I'll be assuming C:\java\eclipse though)

Install ANT
Get newest version
Install: Follow instructions at the URL above

Setting up the project

Launch Eclipse
    Select Java Project
Click Ok
Project Name = "hibernatetutorial"
Click Next
Make sure the source tab is selected and click the Add Folder button
Click the "Create New Folder" button
    Type in "src"

 Click OK 

Click Yes to the "Do you want to..." message
Click Finish
Minimize Eclipse, we're done using it for now

Create the staging folder
Note: I picked C:\hibernatetutorial, you can use whatever you like, but I'll be assuming C:\hibernatetutorial for the rest of this document.

Extract the to C:\hibernatetutorial.  After that you'll need to open a command prompt to c:\hibernatetutorial and type "ant setup-dirs"

OR if you've decided not to use ANT
Create the following directories:

  • C:\hibernatetutorial\apps
  • C:\hibernatetutorial\apps\hibernate
  • C:\hibernatetutorial\apps\hibernate-ext
  • C:\hibernatetutorial\apps\middlegen
  • C:\hibernatetutorial\apps\spring
  • C:\hibernatetutorial\apps\xdoclet
  • C:\hibernatetutorial\apps\hsqldb
  • C:\hibernatetutorial\lib
  • C:\hibernatetutorial\lib\hibernate
  • C:\hibernatetutorial\lib\spring
  • C:\hibernatetutorial\lib\xdoclet
  • C:\hibernatetutorial\lib\hsqldb
  • C:\hibernatetutorial\hsqldb
  • C:\hibernatetutorial\downloads (optional - used for storing the downloads)

Time to install some software

Note: Every "extract the zip file..." line below means extract the zip file directly to the folder.  Do not change the root dir and/or "extract to FILENAME directory."  There may be some repetitive folder names, just ignore them (ex. C:\hibernatetutorial\apps\hsqldb\hsqldb ). If you change the root directory you'll need to manually edit the build.xml, I've provided, to point to the correct application roots.  Additionally, if any of the versions of the software listed below change you'll need to update the build.xml.

Install HSQLDB

File used in this tutorial:
Install: Extract the zip file to the hsqldb directory within the apps directory

Install Hibernate

File used in this tutorial:
Install: Extract to the hibernate directory inside the apps directory

Install Hibernate extensions

File used in this tutorial:
Install: Extract to the hibernate-ext directory inside the apps directory
Install Middlegen
File used in this tutorial:
Install: Extract to the middlegen directory inside the apps directory

Open a command prompt to c:\hibernatetutorial and type "ant setup-middlegen"

OR if you've decided not to use ANT

Copy the following files:

  • C:\hibernatetutorial\apps\hibernate\lib\commons-lang-1.0.X.jar
  • C:\hibernatetutorial\apps\hibernate\hibernate2.jar
  • C:\hibernatetutorial\apps\hibernate-ext\tools\lib\jdom.jar
  • C:\hibernatetutorial\apps\hibernate-ext\tools\hibernate-tools.jar

to the C:\hibernatetutorial\apps\middlegen\lib directory

Delete the following directories / files:

  • C:\hibernatetutorial\apps\middlegen\build
  • C:\hibernatetutorial\apps\middlegen\src
  • C:\hibernatetutorial\apps\middlegen\build.xml
  • C:\hibernatetutorial\apps\middlegen\config\database\hsqldb.xml

Copy the build.xml, provided in the, to C:\hibernatetutorial\apps\middlegen\.  Additionally, copy the hsqldb.xml to the C:\hibernatetutorial\apps\middlegen\config\database\hsqldb.xml.

Install XDoclet

File used in this tutorial:
Install: Extract to the xdoclet directory

Install Spring Framework

File used in this tutorial:
Install: Extract to the spring directory inside the apps directory

Gather up all the jars for our app

Open a command prompt to c:\hibernatetutorial and type "ant copy-jars-to-lib"

OR if you've decided not to use ANT

Hibernate Jars

Copy all the jars from the C:\hibernatetutorial\apps\hibernate\lib
Copy the hibernate2.jar from the C:\hibernatetutorial\apps\hibernate\
to C:\hibernatetutorial\lib\hibernate

Spring Jars

Copy all the jar and dtd files from C:\hibernatetutorial\apps\spring\dist
Copy aopalliance.jar from C:\hibernatetutorial\apps\spring\lib\aopalliance
to C:\hibernatetutorial\lib\spring


Copy the hsqldb.jar from C:\hibernatetutorial\apps\hsqldb\lib to C:\hibernatetutorial\lib\hsqldb

Setup the HSQLDB database

Launch the HSQLDB GUI

Launch a command prompt to c:\hibernatetutorial\lib\hsqldb directory.
Launch the HSQLDB GUI by typing "java -cp hsqldb.jar org.hsqldb.util.DatabaseManager"
    Set the type to: HSQL Database Engine Standalone
    Set the URL to: jdbc:hsqldb:../../hsqldb/hibernatetutorial
    Leave the rest of the settings alone
    Click Ok

Two files were just created that make up the hibernatetutorial database

  • C:\hibernatetutorial\hsqldb\
  • C:\hibernatetutorial\hsqldb\hibernatetutorial.script

Create the GROUPS Table

Paste the following code into the text box next to the execute button

group_id int NOT NULL IDENTITY,
registration_date DATE NOT NULL,
annual_budget decimal(20,4) NOT NULL

Hit execute

Create the USERS Table

Paste the following code into the text box next to the execute button




salary decimal(20,4) NOT NULL,

active bit DEFAULT 'true' NOT NULL,

foreign key (group_id) references groups (group_id)


Hit execute
Close the GUI but leave the console open, we'll be using it in a minute.
Launch the HSQLDB Server
You've just created the groups and users tables we'll be using in our tutorial.  Now all we have to do is launch the HSQLDB Server so we can access the database easily from our application.

Open another command prompt to the C:\hibernatetutorial\hsqldb directory.  Make sure you don't use the command prompt we launched the HSQLDB GUI from, create another command prompt, because we'll be using it in a minute to test our database. Launch the HSQLDB server by typing "java -cp ../lib/hsqldb/hsqldb.jar org.hsqldb.Server -database hibernatetutorial" at the command prompt.  If all went as planned you should see something similar to "Wed Apr 28 17:45:44 EDT 2004 Listening for connections ..." at the bottom of the command prompt.  However, if you see "java.sql.SQLException: The database is already in use by another process", make sure you've closed the HSQLDB GUI.

Relaunch the HSQLDB GUI. 
    Set the type to: HSQL Database Engine Server
    Leave the rest of the settings alone
    Click Ok

Assuming everything has gone smoothly you should see the GROUPS and USERS tables in the lefthand tree.  Congratulations, you're HSQLDB is now fully operation and you're ready to move on to generating you first Hibernate Mapping files. Once again, leave the HSQLDB GUI open.

Using Middlegen

Launching Middlegen

Open a command prompt to C:\hibernatetutorial\apps\middlegen\Middlegen-Hibernate-r4 and type "ant middlegen." You should now see a screen containing your GROUPS and USERS tables. Click on the title bar of the GROUPS table and change the Key Generator type to "Native." Repeat the same process for USERS table. Click the Generate button and wait for it to turn back to light grey. Close the Middlegen GUI.

In the C:\hibernatetutorial\apps\middlegen\Middlegen-Hibernate-r4 directory there should be two new directories, src and build. Navigate to C:\hibernatetutorial\apps\middlegen\build\gen-src\com\warfrog\hibernatetutorial\hibernate; there should be two files Group.hbm.xml and User.hbm.xml. Open the Group.hbm.xml for editing, we need to make a slight modification. Once you've opened the Group.hbm.xml, scroll down till you see the <set> tag (near the bottom) and add the line:


below 'inverse="true". The <set> tag should now look like this:


Additionally, add


below the "inverse="true"" within the <meta> tag. These modifications inform hibernate that when a Group object is saved it should also save and/or update all the User objects associated to the Group. Save the Group.hbm.xml and exit your editor.

At the middlegen command prompt type "ant hbm2java". Assuming that all went well you should see two new .java files ( and inside the C:\hibernatetutorial\apps\middlegen\Middlegen-Hibernate-r4\build\gen-src\com\warfrog\tutorial\hibernate directory. Both java files should contain all the Hibernate XDoclet information required to generate the Group and User hbm.xml files and from the hbm.xml files you can generate the Database schema using the hbm2ddl tool, gotta love full circle development.

Using Hibernate

Setup the Eclipse Project

Open a command prompt to c:\hibernatetutorial and type "ant setup-eclipse-project"

OR if you've decided not to use ANT

Move to C:\java\eclipse\workspace\hibernatetutorial. Copy the "com" directory from the C:\hibernatetutorial\apps\middlegen\build\gen-src\ directory to C:\java\eclipse\workspace\hibernatetutorial\src.  Additionally, copy C:\hibernatetutorial\lib directory to C:\java\eclipse\workspace\hibernatetutorial. Finally, copy all the files from the\project files into C:\java\eclipse\workspace\hibernatetutorial.

Add the JARs to your eclipse classpath

First, right click on the "hibernatetutorial" folder icon and select "Refresh". Now, right click on the "hibernatetutorial" folder icon and select Properties. Click on the Java Build path, then the "Libraries" tab and hit the "Add JARs" button.  Navigate to your hibernatetutorial\lib directory and add all the jars from each folder (hibernate, hsqldb, spring, etc.).  Once you've selected all of the jars, click the Ok button.

Note: use SHIFT+ LEFT_CLICK to select a "block" of jars.

Testing your Hibernate project

Double click on the (found under default package inside eclipse), then click the arrow on the right hand side of the "running man" icon, then select Run As->Java Application. Click Ok to any prompts. If you've setup everything correctly, you should see a bunch of data scroll and some insert statements executing. Execute "SELECT * FROM GROUPS" inside the HSQLDB GUI and "SELECT * FROM USERS" to verify that the data is in the database. One record should be returned from the GROUPS table and 5 records from the USERS table.  Congratulations, you now have a working Hibernate program.

Adding in Spring

Adding Spring into the mix

I've provided the required files to integrate Spring into the project (,, applicationContext.xml,, and  The UserDAO object provides a few sample "find" methods to simply retrieval of User objects.  Additionally, the applicationContext.xml provides information to the Spring framework about sessions, transactions, etc.

Named Queries

A nice feature of Hibernate is the ability to place queries outside of code and in the .hbm.xml files, called named queries.  In this section we'll modify the User.hbm.xml and insert a named query.  Open the User.hbm.xml inside Eclipse for editing.  Depending on your settings you may have to right click on the User.hbm.xml and select Open With -> Text Editor.  Scroll down to the bottom of the file and modify


to this:

    <query name="UsersByDobRange">
       <![CDATA[from User user where user.dob between ? AND ?]]>

Testing your Hibernate Spring project

Double click on the (found under the default package inside eclipse), then click the arrow on the right hand side of the "running man" icon, then select Run As->Java Application. Click Ok to any prompts. If you've setup everything correctly, you should see a bunch of data scroll and SQL statements and then two exceptions being thrown.  The first exception was caught inside a transaction and rolled back when the exception was throw, because we instructed Spring, inside the applicationContext.xml, to "wrap" a transaction around the "addGroupSafe" method of the UserDAOImpl class. The second exception thrown wasn't rolled back, resulting in a "MALFORMED_GROUP_2" group entry being added to our database. You can tell the "addSafe" method call was rolled back by executing "SELECT * FROM GROUPS" in the HSQLDB GUI.  You should see an entry for MALFORMED_GROUP_2, but not MALFORMED_GROUP_1. In the next section we'll make a slight modification to the applicaionContext.xml and wrap both methods in transactions.

Modifying the Transactions

Spring allows you to remove all of the messy session.beginTransaction, commit(), rollback(), etc. code from you method calls.  With Spring you can define what methods utilize transactions and which methods don't using the Application Context.  In this section we'll modify the applicationContext.xml to allow Spring to handle the transaction management for the "malformed" addGroup calls. 

Open the applicationContext.xml inside Eclipse for editing. Once you have the file opened, scroll down to the bottom of the file where you see these lines:


<prop key="addGroupSafe">PROPAGATION_REQUIRED</prop>

<!--<prop key="addGroup*">PROPAGATION_REQUIRED</prop>-->  

modify them so they look like this

<!--<prop key="addGroupSafe">PROPAGATION_REQUIRED</prop>-->
<prop key="addGroup*">PROPAGATION_REQUIRED</prop>

What you've done is told spring to lookout for any method starting with the signature "addGroup" and wrap it in a transaction. Save the modified applicationContext.xml and re-run  Once the program has finished executing, you should notice that both "malformed" save calls where rolled back by Spring.  If you, once again, execute "SELECT * FROM GROUPS" inside the HSQLDB GUI, you'll noticed that no new groups have been inserted into the table.


Launching XDoclet

I've included a build.xml that will allow you to generate hbm.xml files from the Java source files we generated in the MiddleGen section.  Select "Run Ant", making sure the "generate-hbm-from-xdoclet" task is checked and press Ok. You should see some output similar to the lines below:

Buildfile: C:\java\eclipse\workspace\hibernatetutorial\build.xml

[hibernatedoclet] (XDocletMain.start 47 ) Running <hibernate/>
[hibernatedoclet] Generating mapping file for com.warfrog.hibernatetutorial.hibernate.Group.
[hibernatedoclet]     com.warfrog.hibernatetutorial.hibernate.Group
[hibernatedoclet] Generating mapping file for com.warfrog.hibernatetutorial.hibernate.User.
[hibernatedoclet]     com.warfrog.hibernatetutorial.hibernate.User
Total time: 3 seconds

Now, right click on the hibernatetutorial icon and select Refresh. This should cause a new folder,, to appear under your src folder. Inside the xdoclet folder you'll find the Group.hbm.xml and User.hbm.xml files that were generated by XDoclet. If you compare the hbm.xmls generated by Middlegen and hbm.xmls generated by XDoclet you'll notice that Date fields have been converted from type "java.sql.Date" to "java.util.Date." Additionally, you'll notice that XDoclet has inserted some default values that we didn't supply in our Java XDoclet metadata, fortunately neither of these modification should cause any problems.



Hopefully, this tutorial has allowed you to get Hibernate, Spring, Middlegen, and XDoclet working and given you a good basis for building future projects using these great tools.  Additionally, you should now have a development process that allows you to start with a Database, generate the Mappings, generate the Java objects, and start using them quickly.  From theret you can modify the Java objects, regenerate the mappings and using hdm2ddl update the database, if you'd like. As I stated previously, if you have any questions or comments please contact me at either the IRC Handle or the email address listed in the resource section.  If you enjoyed part 1 of this tutorial you should move on to part 2 where I provide additional information on creating Many 2 Many and Inheritance mappings using Hibernate and Middlegen.

  Tyler Pitchford
  Senior Developer -


Other tutorials

Warfrog Hibernate tutorial series part 2 - Hibernate / Middlegen:
Introduction to Hibernate:
MiddleGen-Hibernate Example:
Object-relation mapping without the container:
Object to Relational Mapping and Relationships with Hibernate:


Ant Documentation:
Eclipse Documentation:
Hibernate Documentation:
Spring Documentation:
Middlegen Documenation:
XDoclet Documenation:
Hibernate - Xdoclet:
Hibernate - Spring:

IRC Help

#hibernate on
#spring on
#java on

Contact Info

IRC Handle: TdC_VgA
tyler_pitchford <remove>at<remove>


Tutorial Files: