Spring Guide (official website)

xiaoxiao2021-03-06  128

Hibernate / Spring / Middle Gen / 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 does not coverThis tutorial will not review how Hibernate, Spring, Middlegen, or XDoclet work. Additionally, this tutorial will not 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

Install Command Prompt Here

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

Install EclipseDownload: eclipse-platform-2.1.X-win32.zip URL: http://www.eclipse.org/downloads/index.phpExtract file to c: / java / eclipse (you can use any directory you like, I ' Ll be assuming c: / java / eclipse though)

Install Antget Newest Versionurl: http://ant.apache.org/manual/index.html Install: Follow Instructions At The URL Above

Setting up the project

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

Click Yes to the "Do You Want To ..." MessageClick Finishminimize Eclipse, We're Done Using It For Now

Create the staging folderNote: 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 nesed to open a commnd prompt to c: / hibernatetutorial and type "ant setup-dirs"

Or if You'Ve Decided Not to Use Antcreate 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 - use 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 HSQLDBDownload:. hsqldb_1_7_X.zipFile used in this tutorial: hsqldb_1_7_1.zipURL: http://sourceforge.net/project/showfiles.php? group_id = 23316 & release_id = 117043 Install: Extract the zip file to the hsqldb directory within the apps directoryInstall HibernateDownload: hibernate-2.1.x.zipFile used in this tutorial: hibernate-2.1.3.zipURL: http://prdownloads.sourceforge.net / hibernate /? sort_by = Date & Sort = Desc Install: Extract to the Hibernate Directory Inside The Apps Dire ctoryInstall Hibernate extensionsDownload: hibernate-extensions-2.1.X.zipFile used in this tutorial: hibernate-extensions-2.1.2.zipURL: http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc Install: Extract to the hibernate-ext directory inside the apps directoryInstall MiddlegenDownload: Middlegen-Hibernate-rX.zipFile used in this tutorial: Middlegen-Hibernate-r4.zipURL: http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc Install : Extract to the Middlegen Directory Inside The Apps Directoryopen 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: / hibernatetututorial / 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 XDocletDownload: xdoclet-bin-1.X.zipFile used in this tutorial: xdoclet-bin-1.2.zipURL: http://sourceforge.net/project/showfiles.php?group_id=31602 Install: Extract to the xdoclet directoryInstall Spring FrameworkDownload: spring-framework-1.0.X-with-dependencies.zipFile used in this tutorial: spring-framework-1.0.1-with-dependencies.zipURL: 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 JarsCopy all the jars from the C: / hibernatetutorial / apps / hibernate / libCopy the hibernate2.jar from the C: / hibernatetutorial / apps / hibernate / to C: / hibernatetutorial / lib / hibernateSpring JarsCopy all the jar and dtd files from C : / hibernatetutorial / apps / spring / distCopy aopalliance.jar from C: / hibernatetutorial / apps / spring / lib / aopalliance to C: / hibernatetutorial / lib / spring HSQLDB JarsCopy the hsqldb.jar from C: / hibernatetutorial / apps / hsqldb / Lib to c: / hibernatetututositial / lib / hsqldbsetup 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 Tablepaste 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 Tablepaste The Following Code Into The Text Box Next To The Execute Button

Create Table Users (user_id int, first_name longvarchar (255) Not null, last_name longvarchar (255) 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 executeClose the GUI but leave the console open, we'll be using it in a minute.Launch the HSQLDB ServerYou'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 do not 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 commit" java.sql.sqlexception: The Database is already in use by another process ", make sales Closed the hsqldb GUI.

Test The HibernateTutorial DatabaseRelaunch 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 mode you've Opened the group.hbm.xml, Scroll Down Till you see the tag (Near the Bottom) and add the line: cascade = "save-update"

BELOW 'Inverse = "True". The Tag Should Now Look Like this:

Name = "users"

Lazy = "true"

Inverse = "True"

Cascade = "Save-Update"

>

Additionally, ADD

Cascade = "Save-Update"

below the "inverse =" true "" within the 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 Projectopen 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 HibernateTututorial.java (Found Under Default Package Inside Eclipse), The 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.

Addin Spring

Add 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. Additional, 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:

Testing your hibernate Spring Project

Double Click on The HibernatespringTutorial.java (Found Under The Default Package Inside Eclipse), 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 was not 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 do not using the Application Context. In THIS Section We'lt.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:

PropAgation_required

PropAgation_required ->

Modify theo the love look like this

propagation_required -> PropAgation_required

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/HibernateTututorial/build.xml

generate-hbm-from-xdoclet: [hibernatedoclet] (XDocletMain.start 47) Running [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 secondsNow, 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 ​​Tha Twe 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 tutorialsWarfrog Hibernate tutorial series part 2 - Hibernate / Middlegen: http://www.warfrog.com/hibernatetutorial2Introduction 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: 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/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 : // bos S.bekk.no/boss/middlegen/project-info.html xdoclet: http://xdoclet.sourceForge.NET/ xdoclet document: http://xdoclet.sourceforge.net/project-info.html hibernate - xdoclet: http : //www.hibernate.org/72.html hibernate - Spring: http://hibernate.bluemars.net/110.htmlirc Help # hibernate on igc.freenode.org # Spring on Irc.Freenode.org # java on IRC .freenode.org

Contact Info

IRC Handle: TDC_VGATYLER_PITCHFORD At Yahoo.com

Downloads

Tutorial Files: hibernatetutorial.zip

转载请注明原文地址:https://www.9cbs.com/read-99259.html

New Post(0)