Anda di halaman 1dari 24

Struts Hibernate

Hibernate is Object-Oriented mapping tool that maps the object view of data into relational database and provides efficient persistence services such as create, read, update and delete (CRUD ! "n this tutorial we will implement small search engine application that shows a search form to the user! User enters search string and presses search button! #truts framewor$ process the re%uest and passes it to the action for further processing! &ction class uses Hibernate to ma$e database calls and retrieves matching records from database and results are displa'ed to the user! (ull e)ample code is provided with the tutorial and 'ou can download and start wor$ing on it for 'our project or to learn #truts and Hibernate "ntegration! *ou can download the source code from here! +! Setting up MySQL Database and table ,his section describes how to setup database and populate it with the data! -e are using .'#/0 Database for this tutorial! 1! Downloading Struts, Hibernate and Integrate It ,his section e)plains 'ou to setup the develop wor$bench for our #truts Hibernate tutorial 2! Writing Hibernate configuration file, POJO class and utorial!"b#!$#l %Hibernate #apping class& "n this section we will write re%uired hibernate objects li$e configuration files and then integrate all the stuffs! 3! De'eloping Hibernate Struts Plugin "n this section we will write Hibernate #truts 4lugin 5ava code and integrate it with the #truts! 6! Writing Web (lient to Searc" t"e database using Struts Hibernate Plugin "n this section we will write web client to test struts 4lugin! -e will be developing a search form to search the tutorials from the table! 7! )uild and testing t"e application "n this section we will build our #truts Hibernate 4lugin &pplication and then test!

Setting up MySQL Database and ables


" am assuming that 'ou have running instance of .'#/0 Database and 'ou $now how to wor$ with the .'#/0 database! ,o access the database 'ou should have valid user name and password!

0et8s now start b' creating the database for our struts- hibernate integration tutorial! Our application is ver' ver' simple and it searches for the $e'words t'ped b' user in the table! ,he database will contain one table 8tutorials8 for holding the tutorials lin$s and descriptions! Here is the complete s%l script for setting up the database! CR9&,9 D&,&:&#9 ;struts-hibernate; < CR9&,9 ,&:09 ;tutorials; ( ;id; "=, =O, =U00 &U,O>"=CR9.9=, , ;shortdesc; ?&RCH&R( 6@ =O, =U00 , ;longdesc; ?&RCH&R( 16@ =O, =U00 , ;pageurl; ?&RCH&R( +@@ =O, =U00 , 4R".&R* A9* ( ;id; ,*49 B .*"#&. < ,he above table holds the short description, long description and url of the tutorials! ,he field 8id8 is the uni%ue identifier for records in the articles table! Here are the details of the each of the fields in the tableC id* Uni%ue $e' for the table s"ortdesc* ,his fields stores the short description of the tutorial! longdesc* ,his field stores the full description about the tutorial pageurl* ,his field is stores the url of the tutorial Run the following %uer' to populate table with tutorials dataC "=#9R, "=,O ;tutorials; ?&0U9# (+, 85#4 ,utorials, Hibernate and struts ,utorials8, 8,his site contains man' %ualit' 5ava, 5#4 ,utorials, Hibernate ,utorials, #truts ,utorials, 5#( ,utorials, R.", .'#/0 ,utorials, #pring ,utorials, source codes and lin$s to other java resources! -e have large number of lin$s to the tutorials on java8, 8httpCDDroseindia!netD8 < "=#9R, "=,O ;tutorials; ?&0U9# (1, 85#4 ,utorial8, 85ava #erver 4ages or 5#4 for short is #un88s solution for developing d'namic web sites! 5#4 provide e)cellent server side scripting support for creating database driven web applications!8, 8httpCDDwww!roseindia!netDjspDjsp!shtml8 < "=#9R, "=,O ;tutorials; ?&0U9# (2, 8#truts ,utorials - 5a$arta #truts ,utorial8, 8,his complete reference of 5a$arta #truts shows 'ou how to develop #truts applications using ant and deplo' on the 5:oss &pplication #erver! &nt script is provided with the e)ample code! .an' advance topics li$e ,iles, #truts ?alidation (ramewor$, 5a8, 8httpCDDwww!roseindia!netDstrutsDinde)!shtml8 <

"=#9R, "=,O ;tutorials; ?&0U9# (3, 8,he Complete #pring ,utorial8, 8#pring is grate framewor$ for development of 9nterprise grade applications! #pring is a light-weight framewor$ for the development of enterprise-read' applications! #pring can be used to configure declarative transaction management, remote access to8, 8httpCDDwww!roseindia!netDspringDinde)!shtml8 < "=#9R, "=,O ;tutorials; ?&0U9# (6, 85ava #erver (aces (5#( ,utorial8, 85ava#erver (aces or 5#( is grate technolog' for the development of user interfaces for web applications! ,he 5ava #erver (aces specification is defined b' 5#R +1E of the 5ava Communit' 4rocess!8, 8httpCDDwww!roseindia!netDjsfD8 < "=#9R, "=,O ;tutorials; ?&0U9# (7, 85boss 2!@ ,utorial8, 8 ,his lesson shows 'ou how to build 'ou web application and install on the 5boss 2!@ application server! &fter the completion of this lesson 'ou will be able to compile, assemble and deplo' 'our 5199 application on 5boss 2!@ application server!8, 8httpCDDwww!roseindia!netDjbossDinde)!shtml8 < "n the above steps we have setup our database! "n the ne)t section we will write java stuffs to integrate struts and hibernate!

Downloading Struts + Hibernate


"n this we will download #truts F Hibernate and setup the development environment! Downloading Hibernate Hibernate is free open source software it can be download from httpCDDwww!hibernate!orgD! ?isit httpCDDwww!hibernate!orgD and then clic$ on the Download lin$ to go to the download page! (rom the download page download the current latest release of Hibernate Core! (or this tutorial " have downloaded Hibernate "ibernate,-!.!.!/ip! Download Struts ,he latest release of #truts can be downloaded from httpCDDstruts!apache!orgDdownload!cgi! (or this tutorial " have download struts-+!1!Gbin!Hip! #ave downloaded file into 'our hard dis$! Downloading 0nt &nt is a free tool under I=U 0icence and is freel' available at httpCDDja$arta!apache!orgDantD , current version of ant is +!7!6! &nt allows the developer to automate the repeated process involved in the development of 5199 application!

Developers can easil' write the script to automate the build process li$e compilation, archiving and deplo'ment! (or this tutorial " am using apache-ant-+!7!6! Download MySQL JD)( Dri'er Download m's%l-connector-java-2!@!+7-ga-bin!jar from here m's%l-connector-java2!@!+7-ga-bin!jar or 'ou can download and use the latest version of m's%l jdbc driver! Cop' the 5D:C driver file (m's%l-connector-java-2!@!+7-ga-bin!jar or latest version to the 1a2arta,to#cat,3!3!45co##on5lib director' of 'our tomcat installation! ,his will add the .'#/0 5D:C driver to the tomcat server! Setting 6p De'elop#ent 7n'iron#ent (irst we will create necessar' directories and moved the re%uired files to the appropriate director'! (ollow the following steps to accomplish thisC +! Create a director' in 'ou cC drive called Struts,Hibernate,Integration! 1! UnHip Downloaded file in the director' 'ou have downloaded #truts! 2! Io to the Jstruts,.!8!4,bin5webappsJ director' and 'ou will find struts, blan2!war, struts,docu#entation!war, struts,e$a#ples!war, struts, #ailreader!war and tiles,docu#entation!war files in the director'! Open struts, blan2!war with -inKip and then clic$ on the J9)tractJ button! -inKip as$s for the director' for e)tracting the file, enter J(*5Struts,Hibernate,IntegrationJ and clic$ on 9)tract button!

3! & new director' will created J(*5Struts,Hibernate,Integration5codeJ and the content of struts,blan2!war is e)tracted in the code director'! 6! =ow we will add the hibernate code to our development environment! 9)tract "ibernate,-!.!.!/ip in the director' where 'ou have downloaded! 7! Cop' J"ibernate-!1arJ from L'our downoaded direvor'MN"ibernate,-!. into (*5Struts,Hibernate,Integration5code5W7),I9:5lib director'! E! Cop' all the librar' files from J"ibernate,-!.5libJ to J(*5Struts,Hibernate, Integration5code5W7),I9:5libJ director'! O! Create an director' libe$t under J(*5Struts,Hibernate,Integration5code5W7), I9:5J ! -e will used this director' to put e)tra jar files! Cop' ser'let,api!1ar file 'our tomcat director' to J(*5Struts,Hibernate,Integration5code5W7), I9:5libe$t; director'! G! Change in the build!)ml fileC Open J(*5Struts,Hibernate, Integration5code5W7),I9:5src5build!$#lJ file in 'our favourite editor and change as instructed belowC a (ind J<property na#e=;ser'let!1ar; 'alue=;>1a'asoft>lib>ser'let!1ar;>?J in the build!)ml file and change it to J<property na#e=;ser'let!1ar; 'alue=;!>libe$t>ser'let,api!1ar;>?J b (ind J<property na#e=;distpat"!pro1ect; 'alue=;>pro1ects>lib;>?J and change it to J<property na#e=;distpat"!pro1ect; 'alue=;!!>!!>dist;>?J c Change J<property na#e=;1dbc8@e$t!1ar; 'alue=;>1a'asoft>lib>1dbc8A@, stde$t!1ar;>?J to J<property na#e=;1dbc8@e$t!1ar; 'alue=;!>libe$t>1dbc8A@, stde$t!1ar;>?J! d Change J<property na#e=;pro1ect!title; 'alue=;Ja2arta Struts )lan2 ;>?J to J<property na#e=;pro1ect!title; 'alue=;BoseIndia!net Struts Hibernate Integration utorial ;>?J e Change J<property na#e=;pro1ect!distna#e; 'alue=;blan2;>?J to J<property na#e=;pro1ect!distna#e; 'alue=;struts"ibernate;>?J e Change J<target na#e=;pro1ect; depends=;clean,prepare,co#pile,1a'adoc;>?J to J<C,,<target na#e=;pro1ect; depends=;clean,prepare,co#pile;>?,,?J *ou can download m' build!)ml fom here! +@! Open console and go to the J(*5Struts,Hibernate,Integration5code5W7), I9:5srcJ director' and t'pe ant to compile the project! ,his show the following out putC CCN#truts-Hibernate-"ntegrationNcodeN-9:-"=(NsrcMant :uildfileC build!)ml cleanC PdeleteQ Deleting director' CCN#truts-Hibernate-"ntegrationNcodeN-9:-"=(Nclas ses

Pm$dirQ Created dirC CCN#truts-Hibernate-"ntegrationNcodeN-9:-"=(Nclasses prepareC resourcesC Pcop'Q Cop'ing + file to CCN#truts-Hibernate-"ntegrationNcodeN-9:-"=(Nclass es compileC projectC distC PjarQ :uilding jarC CCN#truts-Hibernate-"ntegrationNdistNstrutshibernate!j ar PwarQ :uilding warC CCN#truts-Hibernate-"ntegrationNdistNstrutshibernate!w ar PwarQ -arningC selected war files include a -9:-"=(Dweb!)ml which will be ignored (please use web)ml attribute to war tas$ allC :U"0D #UCC9##(U0 ,otal timeC 2 seconds CCN#truts-Hibernate-"ntegrationNcodeN-9:-"=(NsrcM and it will create CCN#truts-Hibernate-"ntegrationNdistNstrutshibernate!war file which 'ou can deplo' on application server to test! You can ignore the warning generated while running the ant build tool. ++! ,o test the application cop' the strutshibernate!war to 'our tomcat webapps dirctor' and start tomcat! +1! Open browser and t'pe httpCDDlocalhostCO@O@DstrutshibernateD! *ou browser page should loo$ li$eC

,his means 'ou have successfull' configured 'our development environment!

Writing Hibernate (onfiguration :iles


"n the previous section we completed the database setup and created re%uired table and populated with the data! "n this section we will write re%uired hibernate configuration files! :or t"is tutorial we need following Hibernate configuration files* Hibernate (onfiguration :ile Hibernate configuration file (hibernate!cfg!)ml is used to provide the information which is necessar' for ma$ing database connections! ,he mapping details for mapping the domain objects to the database tables are also a part of Hibernate configuration file! Here is the code of our Hibernate Configuration (ileC LR)ml versionB8+!@8 encodingB8utf-O8RM LSDOC,*49 hibernate-configuration 4U:0"C J-DDHibernateDHibernate Configuration D,DDD9=J JhttpCDDhibernate!sourceforge!netDhibernate-configuration-2!@!dtdJM Lhibernate-configurationM Lsession-factor'M Lpropert' nameBJhibernate!connection!driver>classJMcom!m's%l!jdbc!DriverLDpropert'M

Lpropert' nameBJhibernate!connection!urlJMjdbcCm's%lCDDlocalhostDstrutshibernateLDpropert'M Lpropert' nameBJhibernate!connection!usernameJMrootLDpropert'M Lpropert' nameBJhibernate!connection!passwordJMLDpropert'M Lpropert' nameBJhibernate!connection!pool>siHeJM+@LDpropert'M Lpropert' nameBJshow>s%lJMtrueLDpropert'M Lpropert' nameBJdialectJMorg!hibernate!dialect!.'#/0DialectLDpropert'M Lpropert' nameBJhibernate!hbm1ddl!autoJMupdateLDpropert'M LS-- .apping files --M <#apping resource=;>roseindia>net>dao>"ibernate> utorial!"b#!$#l;>? LDsession-factor'M LDhibernate-configurationM

4lace hibernate!cfg!)ml file in the source director' e!g! J(*5Struts,Hibernate, Integration5code5src51a'a; ,he Lmapping resourceB88M tag is used to specif' the mapping fileC <#apping resource=;>roseindia>net>dao>"ibernate> utorial!"b#!$#l;>? (ode of utorial!"b#!$#l* LR)ml versionBJ+!@J encodingBJU,(-OJRM LSDOC,*49 hibernate-mapping 4U:0"C J-DDHibernateDHibernate .apping D,DDD9=J JhttpCDDhibernate!sourceforge!netDhibernate-mapping-2!@!dtdJM Lhibernate-mapping auto-importBJtrueJ default-laH'BJfalseJM Lclass nameBJroseindia!net!dao!hibernate!,utorialJ tableBJtutorialsJ M Lid nameBJidJ t'peBJjava!lang!"ntegerJ columnBJidJ M Lgenerator classBJincrementJ DM LDidM Lpropert' nameBJshortdescJ t'peBJjava!lang!#tringJ

columnBJshortdescJ not-nullBJtrueJ lengthBJ6@J DM Lpropert' nameBJlongdescJ t'peBJjava!lang!#tringJ columnBJlongdescJ not-nullBJtrueJ lengthBJ16@J DM Lpropert' nameBJpageurlJ t'peBJjava!lang!#tringJ columnBJpageurlJ not-nullBJtrueJ lengthBJ+@@J DM LDclassM LDhibernate-mappingM 4lace utorial!"b#!$#l file in the source director' e!g! J(*5Struts,Hibernate, Integration5code5src51a'a5roseindia5net5dao5"ibernate5; POJO Ob1ect Here is the code of 5ava :ean object (,utorial!java used to store and retrieve the data from database!
package roseindia.net.dao.hibernate; import java.io.Serializable; public class Tutorial implements Serializable { /** identifier field */ private Integer id; /** persistent field */ private String shortdesc; /** persistent field */ private String longdesc; /** persistent field */ private String pageurl;

/** full constructor */ public Tutorial(Integer id, String shortdesc, String longdesc, Strin g pageurl { this.id ! id; this.shortdesc ! shortdesc; this.longdesc ! longdesc; this.pageurl ! pageurl; " /** default constructor */ public Tutorial( { " public Integer getId( return this.id; " {

public void setId(Integer id this.id ! id; " public String getShortdesc( return this.shortdesc; " {

public void setShortdesc(String shortdesc this.shortdesc ! shortdesc; " public String get#ongdesc( return this.longdesc; " {

public void set#ongdesc(String longdesc this.longdesc ! longdesc; " public String get$ageurl( return this.pageurl; " {

public void set$ageurl(String pageurl this.pageurl ! pageurl; " "

"n this section we have created all the Hibernate related stuffs!

De'eloping Struts Hibernate Plugin


"n this section we will develop java code for Struts Hibernate Plugin! Our Hibernate 4lugin will create Hibernate #ession factor' and cache it in the servlet conte)t! ,his strateg' enhances the performance of the application!

Source (ode Of Hibernate Struts Plugin*


package roseindia.net.plugin; import import import import import import import import import import import java.net.%&#; java'.servlet.Servlet(onte't; java'.servlet.Servlet)'ception; org.hibernate.Session*actor+; org.hibernate.cfg.(onfiguration; org.apache.co,,ons.logging.#og; org.apache.co,,ons.logging.#og*actor+; org.apache.struts.action.-ctionServlet; org.apache.struts.action.$lugIn; org.apache.struts.config..odule(onfig; org.hibernate./ibernate)'ception;

public class /ibernate$lugIn implements $lugIn { private String 0config*ile$ath ! 1/hibernate.cfg.',l1; /** * the 2e+ under 3hich the 4code5Session*actor+ 4/code5 instance is stored * in the 4code5Servlet(onte't4/code5. */ public static final String S)SSI670*-(T6&809)8 ! Session*actor+.cla ss.get7a,e( ; private Session*actor+ 0factor+ ! null; public void destro+( { try{ 0factor+.close( ; "catch(/ibernate)'ception e { S+ste,.out.println(1%nable to close /ibernate Session *actor+: 1 ; e.get.essage( ; " " public void init(-ctionServlet servlet, .odule(onfig config throws Servlet)'ception { S+ste,.out.println(1*************************************1 ; S+ste,.out.println(1**** Initilizing /ibernate$lugIn **********1 ; (onfiguration configuration ! null; %&# config*ile%&# ! null; Servlet(onte't conte't ! null; config*ile%&# ! /ibernate$lugIn.class.get&esource(0config*ile$ath ; conte't ! servlet.getServlet(onte't( ; configuration ! (new (onfiguration( .configure(config*ile%&# ; 0factor+ ! configuration.buildSession*actor+( ; //Set the factor+ into session conte't.set-ttribute(S)SSI670*-(T6&809)8, 0factor+ ; try{

"catch(/ibernate)'ception e { S+ste,.out.println(1)rror 3hile initializing hibernate: 1 ; e.get.e ssage( ; " S+ste,.out.println(1**************** *********************1 ; " /** * Setter for propert+ config*ile$ath. * <para, config*ile$ath 7e3 value of propert+ config*ile$ath. */ public void set(onfig*ile$ath(String config*ile$ath { if ((config*ile$ath !! null == (config*ile$ath.tri,( .length( !! > { throw new Illegal-rgu,ent)'ception(1config*ile$ath cannot be blan2 or null.1 ; " S+ste,.out.println(1Setting ? config*ile$ath? to ?1 ; config*ile$ath ; 1?...1 ; 0config*ile$ath ! config*ile$ath; " /*(Session*actor+ servlet(onte't.get-ttribute (/ibernate$lugIn.S)SSI670*-(T6&809)8 ; */ "

"n our plugin class we have define a variable Aconfig:ilePat" to hold the name of Hibernate (onfiguration file! private #tring >config(ile4ath B JDhibernate!cfg!)mlJ< (ollowing code define the $e' to store the session factor' instance in the #ervlet conte)t! public static final #tring #9##"O=>(&C,OR*>A9* B #ession(actor'!class!get=ame( < ,he init( is called on the startup of the #truts &pplication! On startup the session factor' is initialiHed and cached in the #ervlet conte)t! config(ileUR0 B Hibernate4lug"n!class!getResource(>config(ile4ath < conte)t B servlet!get#ervletConte)t( < configuration B (new Configuration( !configure(config(ileUR0 < >factor' B configuration!build#ession(actor'( < DD#et the factor' into session conte)t!set&ttribute(#9##"O=>(&C,OR*>A9*, >factor' < ("anges to be done in struts,config!$#l file

Configuring Hibernate with #truts is ver' simple wor$ it re%uires 'ou to have hibernate!cfg!)ml in 'our -9:-"=(Dclasses director', and to add the following line to the struts-config!)ml file! Lplug-in class=ameBJroseindia!net!plugin!Hibernate4lug"nJMLDplug-inM esting t"e Plugin :uild 'our application and deplo' on the tomcat server! #tart tomcat server and observe the console output! "t should displa' the following lineC logD1*W0B9 Please initiali/e t"e logD1 syste# properly! EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE EEEE Initili/ing HibernatePlugIn EEEEEEEEEE EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE 0ug F, 8@@G .@*@4*3- 0M org!apac"e!struts!tiles! ilesPlugin initD ,his means 'ou have successfull' configured 'our #truts Hibernate 4lugin with struts application!

De'eloping Struts Web Module


"n this we will be creating search interface for enabling the user to search tutorials! ,his e)ample is an client to test our #truts Hibernate 4lugin! ,he web component of the application consists of the following filesC .! Searc" utorial :or# %Searc" utorial!1sp&* ,his file is used to displa' the search form to the user! Here is the code of search formC
4@< taglib uri!1/tags/strutsAbean1 prefi'!1bean1 @5 4@< taglib uri!1/tags/strutsAht,l1 prefi'!1ht,l1 @5 4ht,l:ht,l locale!1true15 4head5 4title54bean:,essage 2e+!13elco,e.title1/54/title5 4ht,l:base/5 4/head5 4bod+ bgcolor!13hite15 4ht,l:for, action!1/searchTutorial15 4ht,l:errors/5

4table5 4tr5 4td align!1right15 Search Tutorial 4/td5 4td align!1left15 4ht,l:te't propert+! 12e+3ord1 size!1B>1 ,a'length!1B>1/5 4/td5 4/tr5 4tr5 4td align!1right15 4ht,l:sub,it5Search4/ht,l:sub,it5 4/td5 4/tr5 4/table5 4/ht,l:for,5 4/bod+5 4/ht,l:ht,l5

#ave Searc" utorial!1sp in to J(*5Struts,Hibernate,Integration5code5pagesJ director'! 8! Searc" Besult Page %Searc"BesultPage!1sp& ,his page is used to displa' the search result! Here is the code of search result pageC
4@<page language!1java1 i,port!1java.util.*1@5 4@< taglib uri!1/tags/strutsAbean1 prefi'!1bean1 @5 4@< taglib uri!1/tags/strutsAht,l1 prefi'!1ht,l1 @5 4p54font size!1C1 color! 1DE>>>>>1 face!1-rial15Search &esults4/font54/p5 4@ #ist searchresult ! (#ist reFuest.get-ttribute(1searchresult1 ; @5 4@ for (Iterator itr!searchresult.iterator( ; itr.has7e't( ; { roseindia.net.dao.hibernate.Tutorial tutorial ! (roseindia.net.dao.hibernate.Tutorial itr.ne't( ; @5 4p54a href!14@!tutorial.get$ageurl( @515 4font face!1-rial1 size!1B154@! tutorial.getShortdesc( @54/font54/a54br5 4font face!1-rial1 size!1G154@! tutorial.get#ongdesc( @54/font54/p5

4@ " @5 4ht,l:lin2 page!1/pages/SearchTutorial.jsp15 Hac2 to Search $age4/ht,l:lin25

#ave Searc"BesultPage!1sp in to J(*5Struts,Hibernate,Integration5code5pagesJ director'! -! Searc" Ja'a :or# %Searc" utorial0ction:or#!1a'a& ,his is the #truts action form class! Here is the code of the &ction (ormC
package roseindia.3eb; import java'.servlet.http./ttpServlet&eFuest; import org.apache.struts.action.*; public class SearchTutorial-ction*or, extends -ction*or, { private String 2e+3ord!null; public void set9e+3ord(String 2e+3ord { this.2e+3ord!2e+3ord; " public String get9e+3ord( { return this.2e+3ord; " public void reset(-ction.apping ,apping, /ttpServlet&eFuest reFuest { this.2e+3ord!null; " public -ction)rrors validate( -ction.apping ,apping, /ttpServlet&eFuest reFuest -ction)rrors errors ! new -ction)rrors( ; if( get9e+3ord( !! null == get9e+3ord( .length( errors.add(12e+3ord1, ne3 -ction.essage(1error.2e+3ord.reFuired1 ; " return errors; " "

{ 4 I {

D! Searc" 0ction (lass %Searc" utorial0ction!1a'a& ,his is #truts &ction Class of our application! Here is the code of the &ction ClassC

package roseindia.3eb; import java'.servlet.http./ttpServlet&eFuest; import java'.servlet.http./ttpServlet&esponse; import java'.servlet.Servlet(onte't; import java.util.#ist; import import import import org.apache.struts.action.-ction; org.apache.struts.action.-ction*or,; org.apache.struts.action.-ction*or3ard; org.apache.struts.action.-ction.apping;

import roseindia.net.plugin./ibernate$lugIn; import roseindia.net.dao.hibernate.Tutorial; import import import import org.hibernate.Session*actor+; org.hibernate.Session; org.hibernate.criterion.&estrictions; org.hibernate.(riteria;

public class SearchTutorial-ction extends -ction { public -ction*or3ard e'ecute( -ction.apping ,apping, -ction*or, for,, /ttpServlet&eFuest reFuest, /ttpServlet&esponse response throws )'ception{ SearchTutorial-ction*or, for,6bj ! (SearchTutorial-ction*or, for,; S+ste,.out.println(1Jetting session factor+1 ; /*Jet the servlet conte't */ Servlet(onte't conte't ! reFuest.getSession( .getServlet(onte't( ; /*&etrieve Session *actor+ */ Session*actor+ 0factor+ ! (Session*actor+ conte't.get-ttribute(/ibernate$lugIn.S)SSI670*-(T6&809)8 ; /*6pen /ibernate Session */ Session session ! 0factor+.openSession( ; //(riteria Kuer+ )'a,ple (riteria crit ! session.create(riteria(Tutorial.class ; crit.add(&estrictions.li2e(1shortdesc1, 1@1 ; for,6bj.get9e+3ord( ;1@1 ; //#i2e condition //*etch the result fro, database #ist tutorials! crit.list( ; reFuest.set-ttribute(1searchresult1,tutorials ; /*(lose session */ session.close( ; S+ste,.out.println(1/ibernate Session (losed1 ; return ,apping.find*or3ard(1success1 ; "

"

3! 7ntries into struts,config!$#l &dd the following lines into 'our struts-config!)ml file! :or# )ean* Lform-bean nameBJ,utorial#earchJ t'peBJroseindia!web!#earch,utorial&ction(ormJM LDform-beanM 0ction 7ntry* Laction pathBJDsearch,utorialJ t'peBJroseindia!web!#earch,utorial&ctionJ nameBJ,utorial#earchJ scopeBJre%uestJ validateBJtrueJ inputBJDpagesD#earch,utorial!jspJM Lforward nameBJsuccessJ pathBJDpagesD#earchResult4age!jspJDM LDactionM =ow we have created all the re%uired stuffs for the web client! "n the ne)t section we will test our application!

)uilding and esting Struts Hibernate Plugin 0pplication


"n this section we will build and test our #truts Hibernate "ntegration application! (o#piling and pac2aging application #ince we are using ant build tool, so the compiling and pac$aging will done b' ant tool! ,o compile and create war file for deplo'ment, open console and go to J(*5Struts, Hibernate,Integration5code5W7),I9:5srcJ director'! ,hen just t'pe ant, ant will create struts"ibernate!war in the J(*5Struts,Hibernate,Integration5distJ director'! Deploying and testing application Cop' struts"ibernate!war to the webapps director' of tomcat and start tomcat server! =ow open the browser and t'pe httpCDDlocalhostCO@O@DstrutshibernateD in the browser! *ou browser should loo$ li$eC

=ow clic$ on JClic$ here to test #earch ,utorialsJ lin$!

9nter some search term sa' JjavaJ and clic$ on search button! *ou browser should displa' the search result as shown below!

Congratulations now 'ou have successfull' integrated 'our struts application with hibernate using Hibernate #truts 4lugin! *ou can download the code of this application from here!

Hibernate 0nnotations
Hibernate 0nnotations e$a#ples and tutorials! +! Quic2 Hibernate 0nnotation utorial ,his tutorial covers onl' the &nnotations part! ,he reader must have hands on e)perience before starting this tutorial! Introduction*, Hibernate needs a metadata to govern the transformation of data from 4O5O to database tables and vice versa! .ost commonl' T.0 file is used to write the metadata information in Hibernate! ,he 5ava 6 (,iger version has introduced a powerful wa' to provide the metadata to the 5?.! ,he mechanism is $nown as &nnotations! &nnotation is the java class which is read through reflection mechanism during the runtime b' 5?. and does the processing accordingl'! ,he Hibernate &nnotations is the powerful wa' to provide the metadata for the Object and Relational ,able mapping! &ll the metadata is clubbed into the 4O5O java file along with the code this helps the user to understand the table structure and 4O5O simultaneousl' during the development! ,his also reduces the management of different files for the metadata and java code!

Hibernate 0nnotations
=oteC- ,his tutorial covers onl' the &nnotations part! ,he reader must have hands on e)perience before starting this tutorial! Introduction*, Hibernate needs a metadata to govern the transformation of data from 4O5O to database tables and vice versa! .ost commonl' T.0 file is used to write the metadata information in Hibernate! ,he 5ava 6 (,iger version has introduced a powerful wa' to provide the metadata to the 5?.! ,he mechanism is $nown as &nnotations! &nnotation is the java class which is read through reflection mechanism during the runtime b' 5?. and does the processing accordingl'! ,he Hibernate &nnotations is the powerful wa' to provide the metadata for the Object and Relational ,able mapping! &ll the metadata is clubbed into the 4O5O java file along with the code this helps the user to understand the table structure and 4O5O simultaneousl' during the development! ,his also reduces the management of different files for the metadata and java code! PrereHuisite for setting t"e pro1ect *, +! .a$e sure 'ou have 5ava 6!@ or higher version ! 1! *ou should have Hibernate Core 2!1!@I& and above! 2! Download and add the Hibernate-&nnotations jar file in the project wor$space! "e :irst 0pplication *, 0et us assume we have a table 9mplo'ee which has onl' two columns i!e "D and =ame! "n hibernate core to achieve the mapping for the above emplo'ee table the user should create the following files C+! 1! 2! 3! 6! Utilit' file for configuring and building the session factor'! Hibernate!cfg!)ml or an' other Datasource metadata file 9mplo'ee 4O5O object! emplo'ee!hbm!)ml file! (,his file is now omitted for the Real application file which has the actual logic manipulate the 4O5O

=oteC- &nnotations are onl' the step to remove the hbm!)ml file so all the steps remain same onl' some modifications in some part and adding the annotation data for the 4O5O! 4lease note that coming e)ample will use the 9mplo'ee table from the database! ,he #/0 %uer' to create the emplo'ee table is as follows C-

Create table Employee( ID int2 PRIMARY EY! "AME n#archar($%& &' Step .*, (reating 6tility (lass *, ,he following is the code given for the utilit' class for session(actor'Cpackage net.roseindia; import org.hibernate.Session*actor+; import org.hibernate.cfg.-nnotation(onfiguration; public class /ibernate%til { private static final Session*actor+ session*actor+; static { try { // (reate the Session*actor+ fro, hibernate.cfg.',l session*actor+ ! new -nnotation(onfiguration( .configure( .buildS ession*actor+( ; " catch (Thro3able e' { // .a2e sure +ou log the e'ception, as it ,ight be s3allo3ed S+ste,.err.println(1Initial Session*actor+ creation failed.1 ; e' ; throw new )'ceptionInInitializer)rror(e' ; " " public static Session*actor+ getSession*actor+( return session*actor+; " {

"

"f 'ou see the onl' change in the file for the annotations is we use &nnotationConfiguration( class instead of the Configuratio( class to build the session(actor' for the hibernate! Step 8* , ,he Hibernate!cfg!)ml is the configuration file for the datasource in the Hibernate world! ,he following is the e)ample for the configuration file! LR)ml versionB8+!@8 encodingB8utf-O8RM LSDOC,*49 hibernate-configuration 4U:0"C J-DDHibernateDHibernate Configuration D,D 2!@DD9=J JhttpCDDhibernate!sourceforge!netDhibernate-configuration-2!@!dtdJM Lhibernate-configurationM Lsession-factor'M LS-- Database connection settings --M

Lpropert' nameBJconnection!driver>classJMcom!m's%l!jdbc!DriverLDpropert'M Lpropert' nameBJconnection!urlJMjdbcCm's%lCDDlocalhostC22@7DtestLDpropert'M Lpropert' nameBJconnection!usernameJMrootLDpropert'M Lpropert' nameBJconnection!passwordJMrootLDpropert'M LS-- 5D:C connection pool (use the built-in --M Lpropert' nameBJconnection!pool>siHeJM+LDpropert'M LS-- #/0 dialect --M Lpropert' nameBJdialectJMorg!hibernate!dialect!.'#/0DialectLDpropert'M LS-- 9nable Hibernate8s automatic session conte)t management --M Lpropert' nameBJcurrent>session>conte)t>classJMthreadLDpropert'M LS-- Disable the second-level cache --M Lpropert' nameBJcache!provider>classJMorg!hibernate!cache!=oCache4roviderLDpropert'M LS-- 9cho all e)ecuted #/0 to stdout --M Lpropert' nameBJshow>s%lJMtrueLDpropert'M LS-- Drop and re-create the database schema on startup --M Lpropert' nameBJhbm1ddl!autoJMnoneLDpropert'M Lmapping classBJcom!roseindia!9mplo'eeJDM LDsession-factor'M LDhibernate-configurationM ,he onl' change is, we are now telling the compiler that instead of an' resource get the metadata for the mapping from the 4O5O class itself li$e in this case it is net!roseindia!9mplo'ee ! 9ote*, 6sing annotations does not #ean t"at you cannot gi'e t"e "b#!$#l file #appng! Iou can #i$ annotations and "b#!$#l files #apping for different Po1o but you cannot #i$ t"e #appings for t"e sa#e Po1o in bot" ways! "is we will discuss furt"er! Step -* ,,he major changes occurred onl' in the 4O5O files if 'ou want to use the annotations as this is the file which will now contain the mapping of the properties with the database! ,he following is the code for the 9mplo'ee 4O5O!
package net.roseindia; import java.io.Serializable; import import import import java'.persistence.(olu,n; java'.persistence.)ntit+; java'.persistence.Id; java'.persistence.Table;

<)ntit+ <Table(na,e ! 1e,plo+ee1 public class ),plo+ee implements Serializable { public ),plo+ee( {

" <Id <(olu,n(na,e ! 1id1 Integer id; <(olu,n(na,e ! 1na,e1 String na,e; public Integer getId( return id; " {

public void setId(Integer id this.id ! id; " public String get7a,e( return na,e; " {

public void set7a,e(String na,e this.na,e ! na,e; " "

"n the 95: word the entities represent the persistence object! ,his can be achieved b' U9ntit' at the class level! U,able(name B Jemplo'eeJ annotation tells the entit' is mapped with the table emplo'ee in the database! .apped classes mu(t declare the primar' $e' column of the database table! .ost classes will also have a 5ava-:eans-st'le propert' holding the uni%ue identifier of an instance! ,he U"d element defines the mapping from that propert' to the primar' $e' column! UColumn is used to map the entities with the column in the database! Step D* ,,he following code demonstrate storing the entit' in the database! ,he code is identical as 'ou have used in theHibernate applications!
package net.roseindia; import org.hibernate.Session; import org.hibernate.Session*actor+; import org.hibernate.Transaction; public class )'a,pleI { /** * <para, args */ public static void ,ain(StringLM args throws )'ception { /** Jetting the Session *actor+ and session */ Session*actor+ session ! /ibernate%til.getSession*actor+( ; Session sess ! session.get(urrentSession( ; /** Starting the Transaction */ Transaction t' ! sess.beginTransaction( ;

/** (reating $ojo */ ),plo+ee pojo ! new ),plo+ee( ; pojo.setId(new Integer(N ; pojo.set7a,e(1O8P1 ; /** Saving $6Q6 */ sess.save(pojo ; /** (o,,iting the changes */ t'.co,,it( ; S+ste,.out.println(1&ecord Inserted1 ; /** (losing Session */ session.close( ; " "

Output *, Becord Inserted! Download t"is 7$a#ple (ode! (onclusion*, ,he above article shows the basic configurations for the Hibernate annotations! ,he above e)ample will onl' add one record in the Database using the hibernate annotations! "n the coming article we will discuss about the various available annotations in the 54& and the also the e)amples demonstrate how to use the annotations for mapping all the hibernate 4O5O to the database tables!

Anda mungkin juga menyukai