Sunteți pe pagina 1din 26

Hibernate Tutorial This is a Hibernate tutorial to help you learn Hibernate and understand how it is used.

By reading this Hibernate tutorial you will learn the main concepts, connect to databases using Hibernate by following real source code examples in the tutorial. Our Hibernate tutorial includes some videos to make it easy to learn.

Introduction to Java Hibernate


Developing enterprise applications involves a lot of efforts to store the business ob ects in the database. !sually,"#$ of the efforts to develop enterprise applications are writing the code to maintain database connections and save the entities to database. %ost of the enterprise applications are developed using Ob ect Oriented techni&ues. The business logic inside the application flows in the form of ob ects instead of textual messages as it used to be in the days of structural programming where we had set of variable to perform operations or indicate the state of an entity. Today,Ob ect Oriented technologies are used to solve the complex problems and maintain the business flow. Only saving the ob ects to the database is a stage where the ob ects are transformed back to text and stored to the database. To understand this problem,consider the following code snippets. This is typically how the connection is obtained in 'ava language.
Class.forName(driverClass); java.s&l.Connection connection = java.sql.DriverManager.getConnection(databaseUrl,databaseUser,databasePass ord); (uppose we have an ob ect of !ser class, and we need to store this ob ect to the database. )onsider the following function* !rivate void saveUser(User "ser) t#ro s $%&'(ce!tion ) Pre!ared$tatement !stmt = connection.!re!are$tatement(*insert into "sers val"es(+,+,+)*); !stmt.set,nt(-,"ser.get,d()); !stmt.set$tring(.,"ser.getName()); !stmt.set$tring(/,"ser.get'mail()); !stmt.set$tring(0,"ser.get1ddress()); !stmt.e(ec"te(); 2

The problem with this code is that this is scattered everywhere in the application which affects the maintainability of the application. There are many problems with this approach like*

)ode is scattered at different un+manageable places. ,f your design changes after developing the application,it will be too expensive to identify the places where changes are re&uired. Difficult to identify and fix the bugs %anaging the database connections is a difficult task since the (-. code is scattered,so are the database connections. %anaging the transactions is a complex task.

Due to these problems,bug fixing is an accepted stage of an application development process which makes the application too expensive even after the successful completion of development cycle. ,t is highly needed to have a mechanism to isolate the database persistent code and write it so efficiently that when there is a change in the database design,it can be easily implemented with the belief that there is no un+identified place which may show a bug later.

Benefits of Relational Database Systems: searching and sorting is fast /ork with large amounts of data /ork with groups of data 'oining, aggregating (haring across multiple users and multiple locations )oncurrency 0Transactions1 (upport for multiple applications )onsistent ,ntegrity )onstraints at different levels Transaction isolation Issues with Relational Database systems: Database %odeling does not support polymorphism Business logic in the application server could be duplicated in the database as stored procedures Does not make use of real world ob ects 2xtra code re&uired to map the 'ava ob ects to database ob ects.

Introduction to Hibernate
Hibernate is an open source ob ect3relational mapping tool for 'ava that lets you develop persistent classes and persistent logic without caring how to handle the data. Hibernate not only takes care of the mapping from 'ava classes to database tables 0and from 'ava data types to (-. data types1,but also provides data &uery and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in (-. and 'DB). Hibernate4s goal is to relieve the developer from 56$ of common data persistence related programming tasks. Hibernate makes it far easier to build robust,high+performance database applications with 'ava. 7ou only need to write a simple 8O'O 08lain Old 'ava Ob ect1,create an 9%. mapping file that describes relationship between the database and the class attributes and call few Hibernate :8,s to load3store the persistent ob ects.

The Object Relational !a""in# $roblem

,n ob ect oriented systems,we represent entities as ob ects and classes and use database to persist those ob ects. %ost of the data+driven applications today,are written using ob ect oriented technologies. The idea of representing entities as set of classes is to re+use the classes and ob ects once written. To understand the scenario,consider a web application that collects users personal information and stores them to the database. :lso there could be a page that displays all the saved users. /hen implementing this kind of solution, we may store the data by getting the re&uest parameters and simply putting it into (-. insert statements. (imilarly when displaying,we can select the desired record from the database,and display them on dynamic web page by iterating through the result set. But wait...does it sound good to have persistent related code scattered everywhere on the web page; /hat if we need to modify the design of our database after we have developed few pages; Or even if we want to replace our low+cost development database with an enterprise+class production database that have entirely different (-. syntax; Do we need to change the (-. &ueries everywhere in our code; To overcome this problem,we may want to develop 'avaBeans representing the entities in the database. /e can develop a 8ersistence %anager that can operate on the given 'avaBean and perform several persistent operations like fetch,store,update,search etc. so that we don4t need to write persistence related code in our core area of application. :dvantage of using this techni&ue is that we can pass on this simple 'avaBean to any of the different layers of the application like a web layer,an 2'B layer or any other layer we may have in our application. /e have isolated our persistence related code so that whenever there is a change in the design,or we change the database environment we can change our persistence code. Or we can have several copies of the 8ersistence %anager to work with different databases so that based on some configuration parameter,we can choose the right 8ersistence %anager instance. But this is still very difficult as we might ignore some database specific settings while writing so many 8ersistence %anagers for different applications. Here the concept of Ob ect <elational mapping comes. By Ob ect <elational mapping 0O3< mapping1 we mean the one+to+one mapping of class attributes with the columns of a database entity. %apping includes the name of the attribute versus database field,the data type,and relation with other entities or classes. (o if we write a framework that can take the ob ect to relation mapping and provide persistence facilities on the given 'avaBeans,we can use it for different applications and different databases. (o,if anyone want to configure the application on a database that was not known at the time of writing the framework,he can simply write a mapping file and the application will start working on that environment. Thanks to the open source community= we don4t need to write such frameworks anymore. /e have Hibernate which allows Ob ect3<elation mapping and provides persistence to the ab ect with the help of simple :8,s where we can specify the operations and the operands 0'avaBeans1.

JDB%
'ava Database )onnectivity 0'DB)1 is a set of :8,s to connect to the database in a standard way. (ince

Hibernate provides Ob ect3<elation mapping,it must communicate to the database of your choice. :nd that cannot happen without the use of a vendor dependent component that understands the target database and the underlying protocol. !sually the database vendors provide set of 4connectors4 to connect with their database from external applications with different set of technologies 3 languages. 'DB) driver is widely accepted connector that provides a fairly standard implementation of the 'DB) specification. The point of discussion of 'DB) here is,that you should know the basics of 'DB) and how to use it with Hibernate. Database connection can be provided by the Hibernate framework or by a '>D, Data source. A third method,user-provided JDBC connections,is also available,but it's rarely used. Typically,in standalone applications,we confi ure the JDBC connection properties in hibernte.cf .!ml file. "n case of applications deployed in an application server,we may choose to use a containermana ed data source,or provide a self-mana ed connection that we mi ht already be usin throu hout the application. #ibernate itself does not impose a restriction to open or confi ure a separate connection for the #ibernate use only and $eep other confi urations to be used by rest of the application. Before startin off with the #ibernate,ma$e sure that you have essential set of JDBC libraries for the database you are oin to use for your application.

The Hibernate &lternative


:s discussed above,Hibernate provides data storage and retrieval by direct mapping of Ob ect and <elation without letting the application developer worry about the persistence logic. There are few alternatives to Hibernate. 7ou may choose to use plain (-. &ueries to store and retrieve data but that is not an alternate to Hibernate as using plain (-. &ueries does not provide maximum of the features provided by Hibernate. 7ou can use 2nterprise 'ava Beans. ,n particular,2ntity Beans are good alternate to Hibernate. But again,you need to see if you really have the re&uirements of an 2'B container; 7ou can use the spring framework 0www.springframework.org1 to implement a D:O layer which would centrali?e as well as minimi?e any future need to change persistence implementations.

There are many other Ob ect3<elation mapping products available like O'B 0Ob'ect<elationalBridge1,Tor&ue,)astor,)ayenne,T'DO etc. @or more details see http*33 ava+ source.net3open+source3persistence

Hibernate &rchitecture and &$I


Hibernate is written in 'ava and is highly configurable through two types of configuration files. The first type of configuration file is named #ibernate.cfg.xml. On startup,Hibernate consults this 9%. file for its operating properties,such as database connection string and password,database dialect,and mapping files locations. Hibernate searches for this file on the classpath. The second type of configuration file is a mapping description file 0file extension 3.#bm1 that instructs Hibernate how to map data between a specific 'ava class and one or more database tables. >ormally in a single application,you would have one hibernate.cfg.xml file,and multiple .hbm files depending upon the business entities you would like to persist. Hibernate may be used by any 'ava application that re&uires moving data between 'ava application ob ects and database tables. Thus,it4s very useful in developing two and three+tier 'A22 applications. ,ntegration of Hibernate into your application involves*

,nstalling the Hibernate core and support ':< libraries into your pro ect )reating a Hibernate.cfg.xml file to describe how to access your database (electing appropriate (-. Dialect for the database. )reating individual mapping descriptor files for each persistable 'ava classes

Here are some commonly used classes of Hibernate. 1.5.1 SessionFactory (org.hibernate.SessionFactory) (ession@actory is a thread safe 0immutable1 cache of compiled mappings for a single database. !sually an application has a single (ession@actory. Threads servicing client re&uests obtain (essions from the factory. The behavior of a (ession@actory is controlled by properties supplied at configuration time. 1.5.2 Session (org.hibernate.Session) : session is a connected ob ect representing a conversation between the application and the database. ,t wraps a 'DB) connection and can be used to maintain the transactions. ,t also holds a cache of persistent ob ects,used when navigating the ob ects or looking up ob ects by identifier. 1.5.3 Transaction (org.hibernate.Transaction) Transactions are used to denote an atomic unit of work that can be committed 0saved1 or rolled back together. : transaction can be started by calling session.begin4ransaction() which actually uses the transaction mechanism of underlying 'DB) connection,'T: or )O<B:.: (ession might span several Transactions in some cases. : complete list of Hibernate :8,s can be found at http*33www.hibernate.org3hibBdocs3vC3api3.

Settin# '" Hibernate


This section will explain how to get the Hibernate distribution and configure the application with hibernate. D. The Hibernate distribution is available at http*33www.hibernate.org3E.html. Download and un?ip the core package from this page. A. Download and install 'DF D.G 0(un or ,B%1 http*33 ava.sun.com3 Ase3downloads3index.html C. Download and install 2clipse C.%.& from http*33www.eclipse.org3downloads3download.php;fileH3eclipse3downloads3drops3<+C.A.D+ A##E#5AD#5G63eclipse+(DF+C.A.D+winCA.?ip . #owever,if you have any other version of 'clipse,that will wor$ too.

G. Download and ,nstall Oracle or %y(-. Database whichever is convenient to you. /e will use Oracle Database D#g 2xpress 2dition. However we will let you know the appropriate steps for %y(-. as well wherever necessary.
6. <un the 2clipse ,D2 and create a simple 'ava 8ro ect as shown below.

Settin# u" Hibernate ( &dd the Hibernate libraries


:dd the Hibernate libraries to the pro ect as shown below. Hibernate libraries can be found at the location where you downloaded and un?ipped the Hibernate distribution.

Re#istration %ase Study


To demonstrate the different steps involved in a Hibernate application,/e will develop a console based application that can add,update,delete or search a user in the database. :s discussed previously,we can use Oracle or %y(-. database for storing the user information. (e)ll use a sin le table *users) to store the user information with the followin fields+
COLUMN NAME USER_ID FIRST_NAME LAST_NAME AGE
2%:,.

DATA TYPE NUMBER TEXT TEXT NUMBER TEXT

CONSTRAINTS PRIMARY KEY NONE NONE NONE NONE

)reate this table in the database. The syntax for the oracle is given below. CREATE TABLE USERS( USER_ID NUMBER PRIMARY KEY, FIRST_NAME VARCHAR(20), LAST_NAME VARCHAR(20), AGE NUMBER, EMAIL VARCHAR(40) ); I !"# $%& #'()* M!S+L ,$-$.$'&,!"# /$) /%&$-& -0& -$.1& #'()* "11"2()* '!)-$34 CREATE TABLE USERS( USER_ID NUMERIC PRIMARY KEY, FIRST_NAME CHAR(20), LAST_NAME CHAR(20), AGE NUMERIC, EMAIL CHAR(40) );

%reatin# the Hibernate %onfi#uration


>ow it is the time to create our Hibernate configuration file. This file will contain the hibernate session configuration like the database driver,user name and password or a '>D, data source if you would like to use one,cache provider ad other session parameters. :lso this file contains the entries for Ob ect to <elation mapping that we will create later. ,nitially let4s create the file with minimum re&uired information and understand what does that information mean.

)reate a new file #ibernate.cfg.(ml in src folder and add the following contents to this file.
I;xml versionH4D.#4 encodingH4utf+J4;K I=DO)T782 hibernate+configuration 8!B.,) L+33Hibernate3Hibernate )onfiguration DTD C.#332>L Lhttp*33hibernate.sourceforge.net3hibernate+ configuration+C.#.dtdLK Ihibernate+configurationK Isession+factoryK Iproperty nameHLconnection.urlLK dbc*oracle*thin*Mlocalhost*D6AD*92 I3propertyK Iproperty nameHLconnection.driverBclassLK oracle. dbc.driver.OracleDriver I3propertyK Iproperty nameHLconnection.usernameLK (7(T2% I3propertyK Iproperty nameHLconnection.passwordLK manager I3propertyK I=++ (et :uto)ommit to true ++K Iproperty nameHLconnection.autocommitLK true I3propertyK I=++ (-. Dialect to use. Dialects are database specific ++K Iproperty nameHLdialectLK org.hibernate.dialect.OracleDialect I3propertyK I=++ %apping files ++K Imapping resourceHLcom3visualbuilder3hibernate3!ser.hbm.xmlL 3K I3session+factoryK I3hibernate+configurationK

:s you can see,the session factory configuration is set of few properties re&uired for a database connection. connection)url is the 'DB) !<. re&uired to connect to the database. connection)driver*class is the 'DB) Driver class which we normally use in )lass.for>ame while establishing a connection to the database. connection)username and connection)"assword are the database user name and password respectively. connection)autocommit sets the :utocommit property of the underlying connection. /e have set it to true so that we don4t need to commit the transactions ourselves unless we want to do it intentionally. This configuration is for an Oracle database at my machine. ,f you are unaware of how to build a !<. for an Oracle database,note that the you need to replace 92 with an appropriate (,D of your Oracle database,localhost with the ,8 address of the machine where Oracle is running if not on local machine,and D6AD with the port. ,n most cases,you will only change the (,D and rest of the parameters will remain the same. ,f you are using %y(-.,you should put the appropriate !<.,Driver class name,user name,password and the Dialect name. The Dialect for %y(-. is org.#ibernate.dialect.M5$%&Dialect. Driver class for the %y(-. is com.mys&l.jdbc.Driver and the !<. for %y(-. is dbc*mys&l*33IserverK*IportK3Idatabase+ nameK. The default port for %y(-. is CC#E. The next important step is to add the 'DB) driver ar file to the pro ect libraries ust like we added the struts libraries. @or oracle,it is o dbcDG.?ip or o dbcDG. ar and can be found under Oracle installation3 dbc3lib. @or example,if Oracle 92 is installed in )*Noraclexe,the o dbcDG. ar can be found on the following path. )*NoraclexeNappNoracleNproductND#.A.#NserverN dbcNlib. 7ou can also download it from http*33www.min&.se3products3dbvis3drivers.html freely.7ou can download the %y(-. 'DB) driver freely from http*33dev.mys&l.com3downloads3connector3 36.#.htmll

+ritin# the first Java ,ile


,et)s start with our first -ava class. .emember we have a table /users0 in the database. ,et)s write a simple bean that represents this table.
"ac-a#e com.visualbuilder.hibernateO 3PP P .author QisualBuilder P P3 "ublic class !ser R "rivate lon# user,d H # O "rivate (tring first>ame H LLO "rivate (tring last>ame H LLO "rivate int age H #O "rivate (tring email H LLO "ublic int get:ge01 R return ageO S "ublic void set:ge0int age1 R this.age H ageO S "ublic (tring get2mail01 R return emailO S "ublic void set2mail0(tring email1 R this.email H emailO S "ublic (tring get@irst>ame01 R return first>ameO S "ublic void set@irst>ame0(tring first>ame1 R this.first>ame H first>ameO S "ublic (tring get.ast>ame01 R return last>ameO S "ublic void set.ast>ame0(tring last>ame1 R this.last>ame H last>ameO S "ublic lon# get!ser,d01 R return user,dO S "ublic void set!ser,d0lon# user,d1 R this.user,d H user,dO S S

+ritin# the ma""in# file


%apping files are the heart of O3< mapping tools. These are the files that contain field to field mapping between the class attributes and the database columns. .et4s write a mapping file for the !ser class that we want to persist to the database.
I;/ml versionHLD.#L;K I=DO)T782 hibernate+mapping 8!B.,) L+33Hibernate3Hibernate %apping DTD C.#332>L Lhttp*33hibernate.sourceforge.net3hibernate+mapping+C.#.dtdL K

Ihibernate(ma""in#K Iclass nameHLcom.visualbuilder.hibernate.!serL tableHL!(2<(L K Iid nameHLuser,dL typeHL ava.lang..ongL columnHLuserBidL K I#enerator classHLincrementL 3K I3idK I"ro"erty nameHLfirst>ameL typeHL ava.lang.(tringL columnHLfirstBnameL lengthHLA#L 3K I"ro"erty nameHLlast>ameL typeHL ava.lang.(tringL columnHLlastBnameL lengthHLA#L 3K I"ro"erty nameHLageL typeHL ava.lang.,ntegerL columnHLageL lengthHL+DL 3K I"ro"erty nameHLemailL typeHL ava.lang.(tringL columnHLemailL lengthHLG#L 3K I3classK I3hibernate(ma""in#K :s you can see,we have mapped all of the attributes of the class L!serL to the columns of the table we created previously. >ote the LidL attribute which maps the "ser,d field of class User is defined in a different way than the other properties. The id tag is used to indicate that this is a primary key,and a 6generator7 tag is used to generate the primary key using different techni&ues. /e have used the increment class,but there are also available different classes to support different kind of key generation techni&ues like generating key from a se&uence,selecting from database etc. /e can also use a custom key generator class.

.et us now add the mapping file to the Hibernate configuration file hibernate.cfg.xml. :fter adding the mapping resource entry,the hibernate.cfg.xml looks like this.

I;/ml versionH4D.#4 encodingH4utf+J4;K I=DO)T782 hibernate+configuration 8!B.,) L+33Hibernate3Hibernate )onfiguration DTD C.#332>L Lhttp*33hibernate.sourceforge.net3hibernate+ configuration+C.#.dtdLK Ihibernate(confi#urationK Isession(factoryK I"ro"erty nameHLconnection.urlLK dbc*oracle*thin*Mlocalhost*D6AD*92I3"ro"ertyK I"ro"erty nameHLconnection.driverBclassLKoracle. dbc.driver.OracleDriverI3"ro"ertyK I"ro"erty nameHLconnection.usernameLK(7(T2%I3"ro"ertyK I"ro"erty nameHLconnection.passwordLKmanagerI3"ro"ertyK I=++ (et :uto)ommit to true ++K I"ro"erty nameHLconnection.autocommitLKtrueI3"ro"ertyK I=++ (-. Dialect to use. Dialects are database specific ++K I"ro"erty nameHLdialectLKnet.sf.hibernate.dialect.OracleDialectI3"ro"ertyK I=++ %apping files ++K Ima""in# resourceHLcom3visualbuilder3hibernate3!ser.hbm.xmlL 3K I3session(factoryK I3hibernate(confi#urationK

+ritin# the Business %om"onent


(o far,we have written a !ser class that we want to persist and a mapping file that describes the relationship of each of the attributes of the class to the database columns. /e have also configured the Hibernate (ession@actory 0hibernate.cfg.xml1 to use the !ser.hbm.xml. >ow it is the time to write a business component that can perform different operations on the !ser ob ect.

7.1 Session
Before writing the business component, we need to understand a hibernate 4session4. :s discussed in section D.6,a hibernate session is an instance of org.hibernate.(ession and is obtained by calling open(ession01 of (ession@actory. 2very database operation begins and ends with a (ession. @or example,we can beginTransaction01,save01,update01 or delete01 an ob ect with the help of a (ession. Our business component will use the (ession to perform its business operations.

package com.vis"alb"ilder.#ibernate.client; import org.#ibernate.$ession; import com.vis"alb"ilder.#ibernate.User; 833 3 UserManager 3 @author 9is"al:"ilder 38

public class UserManager ) private $ession session = n"ll; public UserManager($ession session) ) if(session == n"ll) throw new ;"ntime'(ce!tion(*,nvalid session object. Cannot instantiate t#e UserManager*); this.session = session; 2 public void saveUser(User "ser) ) session.save("ser);2 public void "!dateUser(User "ser) ) session."!date("ser); 2 public void deleteUser(User "ser) ) session.delete("ser); 2 2

+ritin# the Test %lient


.et us write a test client that utili?es the different methods of the !ser%anager we have ust introduced. /e will obtain the $ession<actor5 and

open a session and then call different methods of the UserManager to see if they work or not.

package com.vis"alb"ilder.#ibernate.client; import org.#ibernate.3; import org.#ibernate.cfg.Config"ration; import com.vis"alb"ilder.#ibernate.3; public class 4estClient ) 3PThis method builds a default user to check if the Hiernate configuration is working or notP3 public User b"ildUser() ) User "ser = new User(); "ser.set<irstName(*=o#n*); "ser.set&astName(*'lison*); "ser.set1ge(.-); "ser.set'mail(*jo#n>vis"alb"ilder.com*); return "ser; 2 3P This method gets the default (ession@actory configured in hibernate.cfg.xml and opens a session P3 public $ession o!en$ession() ) $ession<actor5 session<actor5 = new Config"ration().config"re().b"ild$ession<actor5(); $ession session =session<actor5.o!en$ession(); return session; 2 public User test$aveUser(UserManager manager) ) User "ser = b"ildUser(); manager.saveUser("ser); (ystem.o"t.!rintln(*User saved it# ,D = * "ser.getUser,d()); return "ser; 2 public void testU!dateUser(UserManager manager,User "ser) ) "ser.set<irstName(*1ndre *); manager."!dateUser("ser); $5stem.o"t.!rintln(*User "!dated it# ,D = * "ser.getUser,d()); 2 public void testDeleteUser(UserManager manager,User "ser) ) manager.deleteUser("ser); $5stem.o"t.!rintln(*User deleted it# ,D = * "ser.getUser,d()); 2 public static void main($tring?@ args) ) 4estClient client = new 4estClient(); $ession session = client.o!en$ession(); UserManager manager = new UserManager(session); User "ser = client.test$aveUser(manager); client.testU!dateUser(manager,"ser); client.testDeleteUser(manager,"ser); session.fl"s#(); 2 2

!ana#in# &ssociations

:ssociation is a relationship of one class to another class known as 4relationships4 in database terminology. !sually the database design involves the master detail tables to represent the relationship of one entity to another. (truts provides a mechanism to manage one+to+many and many+to+many relationships. Before moving forward,let4s create the necessary database tables to show associations. .et4s create a table !#oneAn"mbers to represent phone numbers of a user. @ollowing script can be used to create the table in Oracle. C;'14' 41:&' PBCN'ANUM:';$
( U$';A,D NUM:'; ;'<';'NC'$ U$';$(U$';A,D), NUM:';A4DP' 91;CB1;(EF), PBCN' NUM:';, P;,M1;D G'D(U$';A,D,NUM:';A4DP')

); 4#e

same table can be created in %y(-. using the script given below.

C;'14' 41:&' PBCN'ANUM:';$


( U$';A,D NUM';,C NC4 NU&& ;'<';'NC'$ U$';$(U$';A,D), NUM:';A4DP' CB1;(EF) NC4 NU&&, PBCN' NUM';,C, P;,M1;D G'D(U$';A,D,NUM:';A4DP') );

He #ave t o tables in t#e databaseI U$';$ and t#e PBCN'ANUM:';$ it# one to man5 relations#i! s"c# t#at one User man5 contain F or more !#one n"mbers. Create a class P#oneN"mber and create its ma!!ing file follo ing t#e ste!s to create User class. 4#e code for t#e P#oneN"mber class is s#o n belo . package com.vis"alb"ilder.#ibernate; import ava.io.$erialiJable; 833 3 P#oneN"mber 3 @author 9is"al:"ilder 38 public class P#oneN"mber implements $erialiJable
)

private long "ser,d = F; private $tring n"mber45!e = *#ome*; private long !#one = F; public $tring getN"mber45!e() ) return n"mber45!e;
2

public public public public public


2

void long void long void

setN"mber45!e($tring n"mber45!e)) this.n"mber45!e = n"mber45!e;2 getP#one() ) return !#one;2 setP#one(long !#one) ) this.!#one = !#one;2 getUser,d() ) return "ser,d;2 setUser,d(long "ser,d) ) this."ser,d = "ser,d; 2

Note t#at e #ave made t#e P#oneN"mber class $erialiJeable. 4#is is beca"se e need a com!osite Ke5 in t#is class,and Bibernate req"ires tat t#e class t#at re!resents t#e com!osite Ke5 m"st be $erialiJeable. 4#e ma!!ing file LP#oneN"mber.#bm.(mlL contains follo ing te(t.

I;/ml versionHLD.#L;K I=DO)T782 hibernate+mapping 8!B.,) L+33Hibernate3Hibernate %apping DTD C.#332>L Lhttp*33hibernate.sourceforge.net3hibernate+mapping+C.#.dtdL K Ihibernate(ma""in#K Iclass nameHLcom.visualbuilder.hibernate.8hone>umberL tableHL8HO>2B>!%B2<(L K Icom"osite(idK I-ey("ro"erty columnHL!(2<B,DL nameHLuser,dL typeHL ava.lang..ongL 3K I-ey("ro"erty columnHL>!%B2<BT782L nameHLnumberTypeL typeHL ava.lang.(tringL3K I3com"osite(idK I"ro"erty nameHLphoneL typeHL ava.lang..ongLK Icolumn nameHL8HO>2L precisionHLAAL scaleHL#L 3K I3"ro"ertyK I3classK I3hibernate(ma""in#K :dd the mapping resource for 8hone>umber in hibernate.cfg.xml file. To do this,locate the line Ima""in# resourceHLcom3visualbuilder3hibernate3!ser.hbm.xmlL 3K in the hibernate.cfg.xml file and add the following line ust after this line. Ima""in# resourceHLcom3visualbuilder3hibernate38hone>umber.hbm.xmlL 3K /e want to write few lines of code so that when we select a user,we automatically get all the phone numbers associated with this user. To do this,add a method 4get8hone>umbers4 that returns a list of users in class !ser and 4set8hone>umbers4 that takes a .ist as argument. The complete listing of class !ser after adding these two methods is shown below. package com.vis"alb"ilder.#ibernate; 833 3 @author 9is"al:"ilder 3 38 public class User ) private long "ser,d = F; private $tring firstName = **; private $tring lastName = **; private int age = F; private $tring email = **; private java."til.$et !#oneN"mbers = new java."til.Bas#$et(); public int get1ge() ) return age; 2 public void set1ge(int age) ) this.age = age; 2 public $tring get'mail() ) return email; 2 public void set'mail($tring email) ) this.email = email; 2 public $tring get<irstName() ) return firstName; 2 public void set<irstName($tring firstName) ) this.firstName = firstName; 2 public $tring get&astName() ) return lastName; 2 public void set&astName($tring lastName) ) this.lastName = lastName; 2 public long getUser,d() ) return "ser,d; 2 public void setUser,d(long "ser,d) ) this."ser,d = "ser,d; 2 public java."til.$et getP#oneN"mbers() ) return !#oneN"mbers; 2

public void setP#oneN"mbers(java."til.$et !#oneN"mbers) ) if(!#oneN"mbers M= n"ll) this.!#oneN"mbers = !#oneN"mbers;


S

The phone>umbers HashTable will be used to store all phone numbers associated with this !ser. The new changes are highlighted in gray. /e have added the methods for getting and setting the phone umbers,we need to add the mapping for the phone numbers now. :dd the following block in !ser.hbm.xml before the I3classK tag.
6set name=*!#oneN"mbers* cascade=*all*7 6key col"mn=*U$';A,D*87 6one-to-many class=*com.vis"alb"ilder.#ibernate.P#oneN"mber* 87 68set7

:s you can see,the tags are very simple. The cascade attribute of set tells the Hibernate how to deal with the child records when a parent is deleted or a child is added. >ow it is the time to test our functionality. <emember the Test)lient class where we had few blocks of code explaining the save,update and delete functionality. @or the time being,comment the call to testDeleteUser and replace the contents of method testU!dateUser with the following code. 8hone>umber ph H new 8hone>umber01O ph.set!ser,d0user.get!ser,d011O ph.set>umberType0LOfficeL1O ph.set8hone05CG"6"1O user.get8hone>umbers01.add0ph1O ph H new 8hone>umber01O ph.set!ser,d0user.get!ser,d011O ph.set>umberType0LHomeL1O ph.set8hone05CG"6"1O user.get8hone>umbers01.add0ph1O manager.save!ser0user1O (ystem.out.println0L!ser updated with ,D H L user.get!ser,d011O /e are adding two phone numbers to the recently saved user ob ects. >ote that we even don4t need to save the 8hone>umber. These are automatically saved as we add them to the !ser. -uery the database and see how these instances are persisted. Once you see the values in the database,re+enable the code to delete the !ser ob ect and see what happens with the child 8hone>umber ob ects. (o far,we have dealt with one to many association,we can configure the Hibernate for one to one and many to many associations. @or more details on how to make Hibernate configuration for other kind of associations,see http*33www.hibernate.org3hibBdocs3vC3reference3en3htmlBsingle3Ttutorial+associations

,indin# by "rimary -ey


,n the previous section,we tested the basic functionality of our hibernate application. /ith few lines of code,we were able to perform the basic operations like insert,update and delete on the database table,and add few children without writing a single (-. &uery. ,n enterprise applications,an efficient search mechanism is highly needed. Hibernate provides a set of different techni&ues to search a

persisted ob ect. .et us see a simple mechanism to find an Ob ect by primary key without using a &uery. :dd the following method in !ser%anager class. public User getUser(long "ser,d) ) User "ser = (User)session.get(User.class, new &ong("ser,d)); return "ser; 2 This is the whole logic of finding a user by primary key. .et4s test this code by adding the following method in Test)lient. public void test<ind:5PK(UserManager manager) ) User "ser = manager.getUser(-);88<ind t#e "ser it# id=if("ser == n"ll) ) (ystem.o"t.!rintln(*No "ser fo"nd it# ,D=-*); 2else ) $5stem.o"t.!rintln(*User fo"nd it# ,D=* "ser.getUser,d() *Nn* *NtName=* "ser.get&astName() *Nn* *Nt'mail=* "ser.get'mail() **);
java."til.,terator

n"mbers = "ser.getP#oneN"mbers().iterator(); while(n"mbers.#asNe(t()) ) P#oneN"mber !# = (P#oneN"mber)n"mbers.ne(t(); $5stem.o"t.!rintln(*NtNtN"mber 45!eI* !#.getN"mber45!e() *Nn* *NtNtP#one N"mberI* !#.getP#one()); 2 2 2 :dd the call to this method in main. To do this,add the following line in main.
client.test<ind:5PK(manager);

<eplace the user id D by some reasonable user id that exists in the database and there are few phone numbers added against that user id. 7ou will see the following output. User fo"nd it# ,D=Name='lison 'mail=jo#n>vis"alb"ilder.com N"mber 45!eICffice P#one N"mberIO/0PEP N"mber 45!eIBome P#one N"mberIO/0PEP

Hibernate 0uery 1an#ua#e 2H013


,n the previous section,we tried to find a persisted user by user id which was primary key in that case. /hat if we want to search a user by user name,age or email and none of these attributes is a primary key. Hibernate provides a &uery language similar to the standard (-. to perform operations on the Hibernate ob ects. The advantage of using H-. instead of standard (-. is that (-. varies as different databases are adopted to implement different

solutions,but H-. remain the same as long as you are within the domain of HibernateO no matter which database you are using. .et us learn to embed H-. in our example to find the users with age greater than C#. Before doing this,make sure that you have some of the users over the age of C#.

@or example,i issued the following &uery on my Oracle console to update the age of few users. update users set ageHCD where userBid in06,J,5,DD,DC,DG1O %odify this &uery to include some of the records in your users table. .et4s write the logic to find the users in our business component. :dd the following method in !ser%anager. public ava."til.&ist getUsers:51ge(int min1age) ) org.#ibernate.%"er5 q = session.create%"er5(*from User " Imin1ge*); q.set,nteger(*min1ge*, min1age); return q.list(); 2

#ere ".age 7=

>ote that the &uery uses L!serL which is the ob ect name and not the table name which is L!sersL. (imilarly the Lu.ageL is an attribute of the !ser ob ect and not the column name of the table. (o whatever the name of the table may be,and whatever the presentation of that table or columns at the database level may be,we will use the same standard syntax while communicating with the hibernate. :lso note the parameter Lmin:geL. The parameters in an H-. &uery are represented with L*L0colon1 character and can be bound using the index or the parameter name in org.hibernate.-uery.

.et4s write a piece of ode to test this functionality. :dd the following method in Test)lient. public void test<ind:51ge(UserManager manager) ) java."til.,terator "sers = manager.getUsers:51ge(/F).iterator(); while("sers.#asNe(t()) ) User "ser = (User)"sers.ne(t(); (ystem.o"t.!rintln(*User fo"nd it# ,D=* "ser.getUser,d() *Nn* *NtName=* "ser.get&astName() *Nn* *Nt'mail=* "ser.get'mail() **); java."til.,terator n"mbers = "ser.getP#oneN"mbers().iterator(); while(n"mbers.#asNe(t()) ) P#oneN"mber !#one = (P#oneN"mber)n"mbers.ne(t(); $5stem.o"t.!rintln(*NtNtN"mber 45!eI* !#one.getN"mber45!e() *Nn* *NtNtP#one N"mberI* !#one.getP#one()); 2 2 2 :dd the call to this method in main. To do this,add the following line in main.
client.test<ind:51ge(manager);

<un the program and see that all the users we modified above are displayed with respective phone numbers.

@ollowing points should be kept in mind when working with H-..


+#&%(&' $%& /$'& ()'&)'(-(5&,&3/&6- -0& 7$5$ /1$'' $), $--%(.#-& )$8&'4 H&)/& SELECT $), '&1&/- $%& -0& '$8&,.#- U'&% $), #'&% $%& )"-4 I -0& /1$'' "% 6$/9$*& ,"&' )"- (), $ 61$/& () (86"%-',-0&) -0& ".:&/-' 0$5& -" .& /$11&, 2(-0 -0& 6$/9$*& )$8&4 F"% &3$861&,( /"845('#$1.#(1,&%40(.&%)$-&4U'&% (' )"- (86"%-&,,-0&) -0& ;#&%! 2"#1, .& < %"8 /"845('#$1.#(1,&%40(.&%)$-&4U'&%< $), '" ")4

@or more details on H-.,visit http*33www.hibernate.org3hibBdocs3vC3reference3en3html3&ueryh&l.html

'sin# native S01


,n previous section,we learnt to use the Hibernate -uery .anguage 0H-.1 that focused on the business entities instead of the vendor dependent syntax. This does not mean that we are bound to use the H-. throughout the Hibernate application if we want to perform some database operations. 7ou may express a &uery in (-.,using create$%&%"er5() and let Hibernate take care of the mapping from result sets to ob ects. >ote that you may at any time call session.connection() and use the 'DB) Connection directly. ,f you chose to use the Hibernate :8,,you must enclose (-. aliases in braces. .et4s see how to use the (-. &ueries by adding the functionality to find a user by user id using native (-. in our !ser%anager. :dd the following method in !ser%anager class. "ublic !ser get!serBy,d0lon# user,d1 R org.hibernate.(-.-uery &uery H session.create(-.-uery0LL L(2.2)T u.userBid as Ru.user,dS,u.firstBname as Ru.first>ameS,u.lastBname as Ru.last>ameS,u.age as Ru.ageS,u.email as Ru.emailS L L@<O% !(2<( RuS /H2<2 RuS.userBidHL user,d LL1O &uery.add2ntity0LuL,!ser.class1O ava.util..ist l H &uery.list01O ava.util.,terator users H l.iterator01O !ser user H nullO if0users.has>ext011 user H 0!ser1users.next01O return userO S ,n the above code,the result type is registered using q"er5.add'ntit5(*"*,User.class) so that Hibernate knows how to translate the <esult(et obtained by executing the &uery. :lso note that the aliases in the &uery are placed in braces and use the same prefix LuL as registered in &uery.add2ntity0...1. This way Hibernate knows how to set attributes of the generated ob ect. :lso this way we can eliminate the confusion of attributes when more than one tables are used in &uery and both of them contain the same column name. q"er5.list() actually executes the &uery and returns the <esul(et in the form of list of ob ects. /e knew that this &uery is going to return only one ob ect,so we returned only the first ob ect if available. .et4s test this code by adding the following method in the Test)lient. public void test<ind:5Native$%&(UserManager manager)

) User "ser = manager.getUser:5,d(.); (ystem.o"t.!rintln(*User fo"nd "sing native sql

it# ,D=* "ser.getUser,d() *Nn*

*NtName=* "ser.get&astName() *Nn* *Nt'mail=* "ser.get'mail() **); java."til.,terator n"mbers = "ser.getP#oneN"mbers().iterator(); while(n"mbers.#asNe(t()) ) P#oneN"mber !#one = (P#oneN"mber)n"mbers.ne(t(); $5stem.o"t.!rintln(*NtNtN"mber 45!eI* !#one.getN"mber45!e() *Nn* *NtNtP#one N"mberI* !#one.getP#one()); 2 2 :dd the call to this method in main. To do this,add the following line in main.
client.test<ind:5Native$%&(manager);

Be sure to pass a valid user id to this method that exists in the database with few valid phone numbers. This code will result in the following output. User fo"nd "sing native sql it# ,D=. Name='lison 'mail=jo#n>vis"alb"ilder.com N"mber 45!eICffice P#one N"mberIO/0PEP N"mber 45!eIBome P#one N"mberIO/0PEP @or more details on using native (-. in Hibernate,see Hibernate documentation.

'sin# %riteria 0ueries


(o far we have seen how to use H-. and native (-. to perform certain database operations. /e saw that the H-. was much simpler than the native (-. as we had to provide database columns and the mapping attributes along with mapping classes too to get fully translated ava ob ects in native (-.. Hibernate provides much simpler :8, called )riteria -ueries if our intention is only to filter the ob ects or narrow down the search. ,n )riteria -ueries,we don4t need to provide the select or from clause. ,nstead,we ust need to provide the filtering criteria. @or example name like 4$a4,or id in 0D,A,C1 etc. .ike H-.,the )riteria :8, works on ava ob ects instead on database entities as in case of native (-.. .et4s write a method in !ser%anager to filter the users that have user id within a set of passed user id4s.

public java."til.&ist getUser:5Criteria(&ong?@ items)


) org.#ibernate.Criteria criteria = session.createCriteria(User.class); criteria.add(org.#ibernate.criterion.;estrictions.in(*"ser,d*, items)); return criteria.list(); 2

This method returns the users and associated phone numbers that have one of the user id in items passed as an argument. (ee how a certain filter criteria is entered using ;estrictions class. (imilarly we

can use ;estrictions.liKe,;estrictions.bet een,;estrictions.isNotN"ll,;estrictions.isN"ll and other methods available in ;estrictions class. .et4s write the test code to verify that the filter we provided using )riteria works. :dd the following method in Test)lient. public void test<ind:5Criteria(UserManager manager)) java."til.,terator "sers = manager.getUser:5Criteria(new &ong?@)new &ong(-),new &ong(.)2).iterator(); while("sers.#asNe(t()) ) User "ser = (User)"sers.ne(t(); (ystem.o"t.!rintln(*User fo"nd it# ,D=*Q"ser.getUser,d()Q*Nn* Q *NtName=*Q"ser.get&astName()Q*Nn* Q *Nt'mail=*Q"ser.get'mail() Q **); java."til.,terator n"mbers = "ser.getP#oneN"mbers().iterator(); while(n"mbers.#asNe(t()) ) P#oneN"mber !#one = (P#oneN"mber)n"mbers.ne(t(); $5stem.o"t.!rintln(*NtNtN"mber 45!eI*Q!#one.getN"mber45!e()Q*Nn* Q *NtNtP#one N"mberI*Q!#one.getP#one()); 2 2 2 :dd the call to this method in main. To do this,add the following line in main. client.test@indBy)riteria0manager1O/e passed the two user ids to the function. (o we should get the two users 0if we have in the database with these user id4s1 with appropriate phone number entries if they exist in the database. Here is what gets displayed under my environment. 7ou should ad ust the appropriate user id4s to get the results.
User fo"nd it# ,D=Name='lison 'mail=jo#n>vis"alb"ilder.com N"mber 45!eICffice P#one N"mberIO/0PEP N"mber 45!eIBome P#one N"mberIO/0PEP User fo"nd it# ,D=. Name='lison 'mail=jo#n>vis"alb"ilder.com N"mber 45!eIBome P#one N"mberIO/0PEP N"mber 45!eICffice P#one N"mberIO/0PEP

'sin# &nt to run the "roject


<< Prev: Using Criteria Queries Next: Using Middlegen to generate source >>

,n previous sections,we have learnt the widely used components of Hibernate. Our development environment was eclipse and a set of Hibernate libraries. !sually ant is used to build and run the Hibernate applications. ,n this section,we will configure our pro ect to use ant and build without any help of eclipse even from command line. To start with ant*

Download and install the latest available version :pache :nt from 0--6=>>$)-4$6$/0&4"%* S&- &)5(%")8&)- 5$%($.1& 7AVA_HOME -" 6"()- -" -0& $5$(1$.1& 7DK 1"/$-(") 1(9& ,=?:$5$?:2',9@4442_04 S&- &)5(%")8&)- 5$%($.1& ANT_HOME -" 6"()- -" -0& $)- ()'-$11$-(") ,(%&/-"%! 1(9& ,=?:$5$?$6$/0&A$)-A@4B42 A,, CANT_HOMEC?.() -" !"#% PATH &)5(%")8&)- 5$%($.1& '" -0$- -0& $)- .()$%(&' $%& $//&''(.1&4

Our ant installation is ready. .et4s configure our pro ect to use ant. )reate a directory lib at the root of our pro ect and place the libraries re&uired by our pro ect in this folder. The libraries include all the Hibernate ar files we added in eclipse pro ect libraries and the 'DB) driver. (ee the directory structure below to find where to place the libraries.

)reate an xml file at the root of the pro ect. i.e. where the src and lib residesO and add the following text in this file. 6+xml version=*-.F*+7 6project name=*#ibernateRt"torial* defa"lt=*r"n* basedir=*.*7
6MRR set global !ro!erties for t#is b"ild RR7 6property name=*srcdir* val"e=*src*87 6property name=*jardir* val"e=*jars*87 6property name=*b"ilddir* val"e=*b"ild*87 6property name=*libdir* val"e=*lib*87 6property name=*!acKage* val"e=*com8vis"alb"ilder8#ibernate*87 6path id=*c!*7 6fileset dir=*S)libdir2*7 6include name=*3.jar*87 6include name=*#ibernate83.jar*87 6include name=*#ibernate8lib83.jar*87 68fileset7 68path7 6target name=*init*7 6mkdir dir=*S)b"ilddir2*87 6mkdir dir=*S)jardir2*87 68target7 6target name=*clean*7 6delete q"iet=*tr"e* dir=*S)b"ilddir2*87 6delete q"iet=*tr"e* dir=*S)jardir2*87 68target7 6target name=*com!ile* de!ends=*init*7 6javac srcdir=*S)srcdir2* destdir=*S)b"ilddir2* class!at#ref=*c!*7 6include name=*S)!acKage283. ava*87 6include name=*S)!acKage28client83.java*87 68javac7 68target7 6target name=*jar* de!ends=*com!ile*7 6jar destfile=*S)jardir28a!!.jar*7 6fileset dir=*S)b"ilddir2*7 6include name=*S)!acKage283383.class*87 68fileset7 6fileset dir=*S)srcdir2*7 6include name=*S)!acKage283.#bm.(ml*87 6include name=*3.cfg.(ml*87 68fileset7 68jar7 68target7 6target name=*r"n* de!ends=*jar*7 6java classname=*com.vis"alb"ilder.#ibernate.client.4estClient* class!at#ref=*c!*7 6classpath7 6pathelement location=*S)jardir28a!!.jar* 87 68classpath7 68java7 68target7 68project7

This is the main build script that can be used to automatically build the source,copy the configuration files0P.hbm.xml and P.cfg.xml1,build the ar file and execute the program. Open the command prompt,change your current directory to the pro ect root,and issue the following command* ant The out put of this command is shown below* 2*Neclipsepro ectsNhibernate+tutorialKant Buildfile* build.xml init* UmkdirV )reated dir* 2*Neclipsepro ectsNhibernate+tutorialNbuild UmkdirV )reated dir* 2*Neclipsepro ectsNhibernate+tutorialN ars compile* U avacV )ompiling G source files to 2*Neclipsepro ectsNhibernate+tutorialNbuild ar* U arV Building ar* 2*Neclipsepro ectsNhibernate+tutorialN arsNapp. ar run* U avaV logG */:<> >o appenders could be found for logger 0org.hibernate.cfg.2nvironment1. U avaV logG */:<> 8lease initiali?e the logG system properly. U avaV !ser found with ,DHDG U avaV >ameH2lison U avaV 2mailH ohnMvisualbuilder.com U avaV >umber Type*Home U avaV 8hone >umber*5CG"6" U avaV >umber Type*Office U avaV 8hone >umber*5CG"6" U avaV !ser found with ,DHD" U avaV >ameH2lison U avaV 2mailH ohnMvisualbuilder.com U avaV >umber Type*Home U avaV 8hone >umber*5CG"6" U avaV >umber Type*Office U avaV 8hone >umber*5CG"6" B!,.D (!))2((@!. (o,you can see that the ant did a magic for us by doing all the configuration,including the necessary libraries and automatically executing the client program for us.

'sin# !iddle#en to #enerate source


I) 6%&5("#' '&/-("),2& /") (*#%&, "#% application -" #'& $)-4 S" $%,2& 0$5& .&&) 2%(-()* 0& O>R 8$66()* (1&' (0.8) $), 2%(-()* ava code "% -0&8 8$)#$11!4 F%$)91! '6&$9()*,-0&%& (' )" '#/0 )&&, -" 6#- '" 8#/0 & "%- "% -0(' 9(), " '-# $' -0&%& $%& ,( &%&)- -""1' $5$(1$.1& -0$- /$) .& #'&, -" *&)&%$-& 8$66()* (1&' %"8 database $), -0&) :$5$ /",& %"8 -0&'& (1&'4 M(,,1&*&) (' ")& " -0&'& -""1',$), /$) .& ,"2)1"$,&, %"8 0--6=>>'"#%/& "%*&4)&->6%":&/->'0"2 (1&'4606D*%"#6_(,EFB044 G& 2(11 #'& 8(,,1&*&) () "#% .#(1, '/%(6- .#(1,4381 -" *&)&%$-& '"#%/& %"8 ,$-$.$'&4 L&-H' $,, -0& %&;#(%&, 1(.%$%(&' -" "#% 1(. ,(%&/-"%!4 @4 D"2)1"$, $), #)I(6 -0& 8(,,1&*&) ,('-%(.#-(") $1")* 2(-0 -0& ,&6&),&)/(&'4 24 C"6! -0& :$% (1&' %"8 8(,,1&*&) ,('-%(.#-(") 2(-0 ,&6&),&)/(&' -" -0& 1(. ,(%&/-"%!4 A1'" ,"2)1"$, -0& 0(.&%)$-& -""1' ,('-%(.#-(") %"8 0--6=>>0(.&%)$-&4"%*>B40-81 $), 61$/& -0& :$% (1& () 1(. ,(%&/-"%!4 Y"# /$) (), -0& ,&6&),&)/(&' $), -0& -""1' () 8(,,1&*&)>'$861&'>1(. ,(%&/-"%!4 F4 A,, -0& "11"2()* 6%"6&%-(&' () -0& 6%"6&%-(&' '&/-(") " -0& .#(1,4381= J6%"6&%-! )$8&E<0.8,(%< 5$1#&E<0.8< >K J6%"6&%-! )$8&E<,.4#%1< 5$1#&E<J,$-$.$'& /"))&/-(") #%1K< >K J6%"6&%-! )$8&E<,.4,%(5&%< 5$1#&E<J,$-$.$'& ,%(5&% /1$''K< >K J6%"6&%-! )$8&E<,.4#'&%< 5$1#&E<J,$-$.$'& #'&% )$8&K< >K J6%"6&%-! )$8&E<,.46$''2"%,< 5$1#&E<J,$-$.$'& #'&% 6$''2"%,K< >K R&61$/& -0& 5$1#&' " -0& %&'6&/-(5& 6%"6&%-(&' 2(-0 !"#% ,$-$.$'& 7DBC #%1,D%(5&% )$8&,#'&% )$8& $), 6$''2"%,4 G& 2(11 #'& -0&'& 6%"6&%-(&' -" *&)&%$-& '"#%/& %"8 '"#%/& ,$-$.$'&4 T0& <0.8,(%< 6%"6&%-! 2(11 6"()- -" -0& 1"/$-(") 20&%& 2& 2$)- -" 61$/& 0.8 (1&'4 44 A,, -0& "11"2()* 1()& () <()(-< -$%*&-= J89,(% ,(%E<LM0.8,(%N<>K O4 A,, -0& "11"2()* 1()& () </1&$)< -$%*&- '" -0$- -0& 0.8 ,(%&/-"%! (' $1'" ,&1&-&, 2(-0 "-0&% .#(1, ,(%&/-"%(&'4 J,&1&-& ;#(&-E<-%#&< ,(%E<LM0.8,(%N<>K

B4 A,, -0& "11"2()* -$%*&- () .#(1,4381= Jtarget )$8&E<*&)A0.8< ,&6&),'E<()(-<K Jtaskdef )$8&E<8(,,1&*&)< /1$'')$8&E<8(,,1&*&)4M(,,1&*&)T$'9< /1$''6$-0%& E</6< >K Jmiddlegen $66)$8&E<0(.&%)$-&A-#-"%($1< 6%& ',(%E<LM0.8,(%N< *#(E< $1'&< ,$-$.$'&#%1E<LM,.4#%1N< ,%(5&%E<LM,.4,%(5&%N< #'&%)$8&E<LM,.4#'&%N< 6$''2"%,E<LM,.46$''2"%,N< '/0&8$E<< /$-$1"*E<< ()/1#,&V(&2'E< $1'&< K Jtable *&)&%$-&E<-%#&< )$8&E<USERS< >K Jtable *&)&%$-&E<-%#&< )$8&E<PHONE_NUMBERS< >K JPAA P1#*()' AAK Jhibernate ,&'-()$-(")E<LM0.8,(%N< 6$/9$*&E</"845('#$1.#(1,&%40(.&%)$-&< :$5$T!6&M$66&%E<8(,,1&*&)461#*()'40(.&%)$-&4H(.&%)$-&7$5$T!6&M$66&%< >K J>middlegenK Jtaskdef )$8&E<0.82:$5$< /1$'')$8&E<)&-4' 40(.&%)$-&4-""140.82:$5$4H.827$5$T$'9< /1$''6$-0%& E</6< >K Jhbm2 ava "#-6#-E<LM.#(1,4*&)A'%/4,(%N<K Jfileset ,(%E<LM0.8,(%N<K Jinclude )$8&E<QQ>Q40.84381<>K J>filesetK J>hbm2 avaK J>targetK

F#11 /")-&)-' " -0(' (1& $%& *(5&) .&1"2=


6+xml version=*-.F*+7 6project name=*#ibernateRt"torial* defa"lt=*r"n* basedir=*.*7 6MRR set global !ro!erties for t#is b"ild RR7 6property name=*srcdir* val"e=*src*87 6property name=*jardir* val"e=*jars*87 6property name=*b"ilddir* val"e=*b"ild*87 6property name=*libdir* val"e=*lib*87 6property name=*#bmdir* val"e=*#bm* 87 6property name=*db."rl* val"e=*6database connection "rl7* 87 6property name=*db.driver* val"e=*6database driver class7* 87 6property name=*db."ser* val"e=*6database "ser name7* 87 6property name=*db.!ass ord* val"e=*6database "ser !ass ord7* 87 6property name=*!acKage* val"e=*com8vis"alb"ilder8#ibernate*87 6path id=*c!*7 6fileset dir=*S)libdir2*7 6include name=*3.jar*87 6include name=*#ibernate83.jar*87 6include name=*#ibernate8lib83.jar*87 68fileset7 68path7 6target name=*init*7 6mkdir dir=*S)b"ilddir2*87 6mkdir dir=*S)jardir2*87 6mkdir dir=*S)#bmdir2*87 68target7 6target name=*clean*7 6delete q"iet=*tr"e* dir=*S)b"ilddir2*87 6delete q"iet=*tr"e* dir=*S)jardir2*87 6delete q"iet=*tr"e* dir=*S)#bmdir2*87 68target7 6target name=*com!ile* de!ends=*init*7 6javac srcdir=*S)srcdir2* destdir=*S)b"ilddir2* class!at#ref=*c!*7 6include name=*S)!acKage283.java*87 6include name=*S)!acKage28client83.java*87 68javac7 68target7 6target name=*jar* de!ends=*com!ile*7 6jar destfile=*S)jardir28a!!.jar*7 6fileset dir=*S)b"ilddir2*7 6include name=*S)!acKage283383.class*87 68fileset7 6fileset dir=*S)srcdir2*7 6include name=*S)!acKage283.#bm.(ml*87 6include name=*3.cfg.(ml*87 68fileset7 68jar7 68target7 6target name=*r"n* de!ends=*jar*7 6java classname=*com.vis"alb"ilder.#ibernate.client.4estClient* class!at#ref=*c!*7 6classpath7 6pathelement location=*S)jardir28a!!.jar* 87 68classpath7 68java7 68target7

6target name=*genR#bm* de!ends=*init*7 6taskdef name=*middlegen* classname=*middlegen.Middlegen4asK* class!at#ref=*c!* 87 6middlegen a!!name=*#ibernateRt"torial* !refsdir=*S)#bmdir2* g"i=*false* database"rl=*S)db."rl2* driver=*S)db.driver2* "sername=*S)db."ser2* !ass ord=*S)db.!ass ord2* sc#ema=** catalog=** incl"de9ie s=*false* 7 6table generate=*tr"e* name=*U$';$* 87 6table generate=*tr"e* name=*PBCN'ANUM:';$* 87 6MRR Pl"gins RR7 6hibernate destination=*S)#bmdir2* !acKage=*com.vis"alb"ilder.#ibernate* java45!eMa!!er=*middlegen.!l"gins.#ibernate.Bibernate=ava45!eMa!!er* 87 68middlegen7 6taskdef name=*#bm.java* classname=*net.sf.#ibernate.tool.#bm.java.Bbm.=ava4asK* class!at#ref=*c!* 87 6hbm2java o"t!"t=*S)#bmdir2*7 6fileset dir=*S)#bmdir2*7 6include name=*3383.#bm.(ml*87 68fileset7 68hbm2java7 68target7 68project7 Middlegen / is not available 5et,and middlegen ..- does not s"!!ort Bibernate /. $o,to generate java so"rce from #bm "sing Bibernate 4ools,
<eplace the database properties values and run the following command on command prompt while residing in the pro ect root directory* ant #en(hbm This will generate two hbm files in package folders under the hbm directory. /e have separately generated the hbm and source. ,f we ust replace the hbm and the ava files in package com.visualbuilder.hibernate,we will have few conflicts because middlegen has transformed the data types differently. /e have used long for the numeric types,but the middlegen actually represents numeric as BigDecimal. (o there will be few syntax errors in the client onlyO on removing which the code should work smoothly.

Review and the ne/t ste"s


Than-s for readin# the Java Hibernate Tutorial
+hat4s 5e/t6 >ow that you have learnt how to create some simple Hibernate code and grasped the fundamentals of Hiernate programming,you can build on your knowledge and become an expert. !a-e sure you visit our famous JS$ tutorial 2one of the best on the Internet3

)lick here to see the '(8 Tutorial


!ore Tutorials 8lease view our JSP and 'A22 Design Tutorial to learn more about how to use '(8.

)lick here to start the '(8 and 'A22 Design Tutorial


.earn about the '(8 Struts Framework for the next step of practically ising '(8.

'(8 (truts Tutorial 0>ew=1


Join our Java and JS$ 7rou" and we4ll -ee" you u" to date Do you want to be kept up to date with the new '(8 tutorial updates and the latest '(8 code,articles and news; Qisit 'ava Wroup and click the 'oin button. Qisit '(8 Wroup and click the 'oin button. 7ou can start discussing with others learning this technology. ,t4s free and you can set how you want to your email updates.
X QisualBuilder.com A##"

To"1in- is an ob ect+relational mapping 0O<%1 package for 'ava developers. ,t provides a powerful and flexible framework for storing 'ava ob ects in a relational database or for converting 'ava ob ects to 9%. documents. Top.ink 2ssentials UDV is the <eference implementation of the 2'B C.# 'ava 8ersistence :8, 0'8:1 and the open+ source community edition of Oracle4s Top.ink product. Top.ink 2ssentials is a limited version of the proprietary product. @or example, Top.ink 2ssentials doesn4t provide cache synchroni?ation between clustered application, some cache invalidation policy, and &uery )ache.

S-ar putea să vă placă și