编程语言

img phoenixup

Spring指南(官网)

发表于2004/10/29 11:20:00  1916人阅读

分类: Java IDE Spring


Hibernate / Spring / Middlegen / XDoclet Tutorial v1.5

Part 1 in the Warfrog.com 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 hibernatetutorial.zip. 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 irc.freenode.net under the handle TdC_VgA.


Downloading / Installing optional software


Install Command Prompt Here

Download: CmdHere.reg.txt
URL:
http://www.tburke.net/info/win2k/regfiles/CmdHere.reg.txt
Install: Save CmdHere.reg.txt
          Rename CmdHere.reg.txt to cmdhere.reg
          Right click on cmdhere.reg -> Merge


Install Eclipse
Download: eclipse-platform-2.1.X-win32.zip 
URL: http://www.eclipse.org/downloads/index.php
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
URL: http://ant.apache.org/manual/index.html
Install: Follow instructions at the URL above


Setting up the project


Launch Eclipse
File->New->Project
    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 hibernatetutorial.zip 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

Download: hsqldb_1_7_X.zip
File used in this tutorial: hsqldb_1_7_1.zip
URL: http://sourceforge.net/project/showfiles.php?group_id=23316&release_id=117043
Install: Extract the zip file to the hsqldb directory within the apps directory

Install Hibernate

Download: hibernate-2.1.x.zip
File used in this tutorial: hibernate-2.1.3.zip
URL: http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc
Install: Extract to the hibernate directory inside the apps directory

Install Hibernate extensions

Download: hibernate-extensions-2.1.X.zip
File used in this tutorial: hibernate-extensions-2.1.2.zip
URL: http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc 
Install: Extract to the hibernate-ext directory inside the apps directory
Install Middlegen
Download: Middlegen-Hibernate-rX.zip
File used in this tutorial: Middlegen-Hibernate-r4.zip
URL: http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc 
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 hibernatetutorial.zip, to C:/hibernatetutorial/apps/middlegen/.  Additionally, copy the hsqldb.xml to the C:/hibernatetutorial/apps/middlegen/config/database/hsqldb.xml.

Install XDoclet

Download: xdoclet-bin-1.X.zip
File used in this tutorial: xdoclet-bin-1.2.zip
URL: http://sourceforge.net/project/showfiles.php?group_id=31602
Install: Extract to the xdoclet directory

Install Spring Framework

Download: spring-framework-1.0.X-with-dependencies.zip
File used in this tutorial: spring-framework-1.0.1-with-dependencies.zip
URL: http://sourceforge.net/project/showfiles.php?group_id=73357
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

HSQLDB Jars

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/hibernatetutorial.properties
  • C:/hibernatetutorial/hsqldb/hibernatetutorial.script

Create the GROUPS Table

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

 
CREATE TABLE GROUPS (
group_id int NOT NULL IDENTITY,
name LONGVARCHAR(255) NOT NULL,
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

 

CREATE TABLE USERS ( user_id int NOT NULL IDENTITY, group_id int, first_name LONGVARCHAR(255) NOT NULL, last_name LONGVARCHAR(255) NOT NULL, dob DATE NOT NULL, ssn LONGVARCHAR(20) NOT NULL,

phone LONGVARCHAR(20) NOT NULL,

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.

Test the HIBERNATETUTORIAL Database
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:

 
cascade="save-update"
 

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

 
<set
    name="users"
    lazy="true"
    inverse="true"
    cascade="save-update"
>
 

Additionally, add

 
cascade="save-update"
 

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 (Group.java and User.java) 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 hibernatetutorial.zip/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 HibernateTutorial.java (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 (UserDAO.java, UserDAOImpl.java, applicationContext.xml, ApplicationContextFactory.java, and HibernateSpringTutorial.java).  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

 
</class>
</hibernate-mapping>
 

to this:

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

Testing your Hibernate Spring project

Double click on the HibernateSpringTutorial.java (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 HibernateSpringTutorial.java.  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.


XDoclet


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

generate-hbm-from-xdoclet:
[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
BUILD SUCCESSFUL
Total time: 3 seconds


Now, right click on the hibernatetutorial icon and select Refresh. This should cause a new folder, xdoclet.com.warfrog.hibernatetutorial.hibernate, 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.


Conclusion


Conclusion

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.

Cheers,
  Tyler Pitchford
  Senior Developer - Warfrog.com


Resources


Other tutorials

Warfrog Hibernate tutorial series part 2 - Hibernate / Middlegen: http://www.warfrog.com/hibernatetutorial2
Introduction to Hibernate: http://www.systemmobile.com/articles/IntroductionToHibernate.html
MiddleGen-Hibernate Example: http://www.systemmobile.com/articles/IntroductionToHibernate.html
Object-relation mapping without the container: http://www-106.ibm.com/developerworks/library/j-hibern/?ca=dnt-515
Object to Relational Mapping and Relationships with Hibernate: www.meagle.com:8080/hibernate.jsp

Links

Ant: http://ant.apache.org/
Ant Documentation: http://ant.apache.org/manual/index.html
Eclipse: http://www.eclipse.org/
Eclipse Documentation: http://www.eclipse.org/
Hibernate: http://www.hibernate.org
Hibernate Documentation: http://www.hibernate.org/hib_docs/reference/en/html/
Spring: http://www.springframework.org/
Spring Documentation: http://www.springframework.org/documentation.html
Middlegen: http://boss.bekk.no/boss/middlegen/
Middlegen Documenation: http://boss.bekk.no/boss/middlegen/project-info.html
XDoclet: http://xdoclet.sourceforge.net/
XDoclet Documenation: http://xdoclet.sourceforge.net/project-info.html
Hibernate - Xdoclet: http://www.hibernate.org/72.html
Hibernate - Spring: http://hibernate.bluemars.net/110.html

IRC Help

#hibernate on irc.freenode.org
#spring on irc.freenode.org
#java on irc.freenode.org

Contact Info

IRC Handle: TdC_VgA
tyler_pitchford <remove>at<remove> yahoo.com

Downloads

Tutorial Files: hibernatetutorial.zip


 

阅读全文
0 0

相关文章推荐

img
取 消
img