You are on page 1of 72

What is Hibernate? Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.

0 is available for do nload fro! Hibernet.org."he Hibernate 3.0 core is #$,%&' lines of Java code together ith 2(,'&$ lines of unit tests, all freely available under the )*+), and has been in develop!ent for ell over a year. Hibernate !aps the Java classes to the database tables. ,t also provides the data -uery and retrieval facilities that significantly reduces the develop!ent ti!e. Hibernate is not the best solutions for data centric applications that only uses the stored.procedures to i!ple!ent the business logic in database. ,t is !ost useful ith ob/ect.oriented do!ain !odes and business logic in the Java.based !iddle.tier. Hibernate allo s transparent persistence that enables the applications to s itch any database. Hibernate can be used in Java S ing applications, Java Servlet.based applications, or J2EE applications using EJB session beans. Features of Hibernate

Hibernate 3.0 provides three full.featured -uery facilities0 Hibernate Query Language, the ne ly enhanced Hibernate Criteria Query API, and enhanced support for -ueries e1pressed in the native SQL dialect of the database. 2ilters for or3ing ith te!poral 4historical5, regional or per!issioned data. Enhanced 6riteria -uery 7+,0 ith full support for pro/ection8aggregation and subselects. 9unti!e perfor!ance !onitoring0 via J:; or local Java 7+,, including a second.level cache bro ser. Eclipse support, including a suite of Eclipse plug.ins for or3ing ith Hibernate 3.0, including !apping editor, interactive -uery prototyping, sche!a reverse engineering tool. Hibernate is 2ree under )*+)0 Hibernate can be used to develop8pac3age and distribute the applications for free. Hibernate is Scalable0 Hibernate is very perfor!ant and due to its dual.layer architecture can be used in the clustered environ!ents. )ess <evelop!ent "i!e0 Hibernate reduces the develop!ent ti!ings as it supports inheritance, poly!orphis!, co!position and the Java 6ollection fra!e or3. 7uto!atic =ey *eneration0 Hibernate supports the auto!atic generation of pri!ary 3ey for your. J<= >.% Enhance!ents0 "he ne J<= has been released as a previe earlier this year and e e1pect a slo !igration to the ne >.% platfor! throughout 200&. ?hile Hibernate3 still runs perfectly ith J<= >.2, Hibernate3 ill !a3e use of so!e ne J<= features. JS9 >(% annotations, for e1a!ple, are a perfect fit for Hibernate !etadata and e ill e!brace the! aggressively. ?e ill also support Java generics, hich basically boils do n to allo ing type safe collections.

EJB3.style persistence operations0 EJB3 defines the create() and merge() operations, hich are slightly different to Hibernate@s saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 ill support all four operations as !ethods of the Session interface. Hibernate ;:) binding enables data to be represented as ;:) and +OJOs interchangeably. "he EJB3 draft specification support for +OJO persistence and annotations. .hibernate.org87bout89oad:ap.

<etailed features are available at http088

Hibernate Architecture
,n this lesson you ill learn the architecture of Hibernate. "he follo ing diagra! describes the high level architecture of hibernate0

"he above diagra! sho s that Hibernate is using the database and configuration data to provide persistence services 4and persistent ob/ects5 to the application. "o use Hibernate, it is re-uired to create Java classes that represents the table in the database and then !ap the instance variable in the class ith the colu!ns in the database. "hen Hibernate can be used to perfor! operations on the database li3e select, insert, update and delete the records in the table. Hibernate auto!atically creates the -uery to perfor! these operations. Hibernate architecture has three !ain co!ponents0

Connection Management Hibernate 6onnection !anage!ent service provide efficient !anage!ent of the database connections. <atabase connection is the !ost e1pensive part of interacting ith the database as it re-uires a lot of resources of open and close the database connection. Transaction management "ransaction !anage!ent service provide the ability to the user to e1ecute !ore than one database state!ents at a ti!e. !b"ect re#ationa# ma$$ing Ob/ect relational !apping is techni-ue of !apping the data representation fro! an ob/ect !odel to a relational data !odel. "his part of the hibernate is used to select, insert, update and delete the records for! the underlying table. ?hen e pass an ob/ect to a Session%save&' !ethod, Hibernate reads the state of the variables of that ob/ect and e1ecutes the necessary -uery.

Hibernate is very good tool as far as ob/ect relational !apping is concern, but in ter!s of connection !anage!ent and transaction !anage!ent, it is lac3ing in perfor!ance and capabilities. So usually hibernate is being used ith other connection !anage!ent and transaction !anage!ent tools. 2or e1a!ple apache <B6+ is used for connection pooling ith the Hibernate. Hibernate provides a lot of fle1ibility in use. ,t is called ALiteA architecture hen e only uses the ob/ect relational !apping co!ponent. ?hile in AFu## CreamA architecture all the three co!ponent Ob/ect 9elational !apping, 6onnection :anage!ent and "ransaction :anage!ent5 are used.

Writing First Hibernate Co(e


,n this section , ill sho you ho to create a si!ple progra! to insert record in :ySB) database. Cou can run this progra! fro! Eclipse or fro! co!!and pro!pt as ell. , a! assu!ing that you are fa!iliar ith :ySB) and Eclipse environ!ent. Configuring Hibernate ,n this application Hibernate provided connection pooling and transaction !anage!ent is used for si!plicity. Hibernate uses the hibernate.cfg.1!l to create the connection pool and setup re-uired environ!ent. Here is the co(e DE1!l versionF@>.0@ encodingF@utf.$@EG DH<O6"C+E hibernate.configuration +IB),6 A.88Hibernate8Hibernate 6onfiguration <"<88EJA Ahttp088hibernate.sourceforge.net8hibernate.configuration.3.0.dtdAG Dhibernate.configurationG Dsession.factoryG

Dproperty na!eFAhibernate.connection.driverKclassAG co!.!ys-l./dbc.<riverD8propertyG Dproperty na!eFAhibernate.connection.urlAG "(bc mys)# **#oca#host*hibernatetutoria#D8propertyG Dproperty na!eFAhibernate.connection.userna!eAGrootD8propertyG Dproperty na!eFAhibernate.connection.pass ordAGD8propertyG Dproperty na!eFAhibernate.connection.poolKsiLeAG>0D8propertyG Dproperty na!eFAsho Ks-lAGtrueD8propertyG Dproperty na!eFAdialectAGorg%hibernate%(ia#ect%MySQL+ia#ectD8propertyG Dproperty na!eFAhibernate.hb!2ddl.autoAGu$(ateD8propertyG DH.. :apping files ..G D!apping resourceFAcontact%hbm%,m#A8G D8session.factoryG D8hibernate.configurationG ,n the above configuration file e specified to use the Ahibernatetutoria#- hich is running on #oca#host and the user of the database is root ith no pass ord. "he (ia#ect property is org%hibernate%(ia#ect%MySQL+ia#ect hich tells the Hibernate that e are using :ySB) <atabase. Hibernate supports !any database. ?ith the use of the Hibernate 4Ob/ect89elational :apping and "ransparent Ob/ect +ersistence for Java and SB) <atabases5, e can use the follo ing databases dialect type property0

<B2 . org.hibernate.dialect.DB2Dialect HypersonicSB) . org.hibernate.dialect.HSQLDialect ,nfor!i1 . org.hibernate.dialect. n!ormi"Dialect ,ngres . org.hibernate.dialect. ngresDialect ,nterbase . org.hibernate.dialect. nterbaseDialect +ointbase . org.hibernate.dialect.#ointbaseDialect +ostgreSB) . org.hibernate.dialect.#ostgreSQLDialect :c3oi SB) . org.hibernate.dialect.$c%oiDialect :icrosoft SB) Server . org.hibernate.dialect.SQLServerDialect :ySB) . org.hibernate.dialect.$ySQLDialect Oracle 4any version5 . org.hibernate.dialect.OracleDialect Oracle ' . org.hibernate.dialect.Oracle&Dialect +rogress . org.hibernate.dialect.#rogressDialect 2rontBase . org.hibernate.dialect.'rontbaseDialect S7+ <B . org.hibernate.dialect.S(#DBDialect Sybase . org.hibernate.dialect.SybaseDialect Sybase 7ny here . org.hibernate.dialect.Sybase(ny)hereDialect

"he D!apping resourceFAcontact%hbm%,m#A8G property is the !apping for our contact table.

Writing First Persistence C#ass Hibernate uses the +lain Old Java Ob/ects 4+OJOs5 classes to !ap to the database table. ?e can configure the variables to !ap to the database colu!n. Here is the code for 6ontact./ava0
package roseindia.t*torial.hibernate+ ,-.-./a*thor.Deepa%.0*mar ..-.1ava.Class.to.map.to.the.datbase.Contact.2able .-, public class Contact.3 ..private String.!irst4ame+ ..private String.last4ame+ ..private String.email+ ..private long id+ ..,-...-./ret*rn.5mail ...-, ..public String.get5mail().3 ....return email+ ..6 ..,-...-./ret*rn.'irst.4ame ...-, ..public String.get'irst4ame().3 ....return !irst4ame+ ..6 ..,--. ...-./ret*rn.Last.name ...-, ..public String.getLast4ame().3 ....return last4ame+ ..6 ..,-...-./param.string.Sets.the.5mail ...-, ..public void set5mail(String.string).3 ....email.7.string+ ..6 ..,-...-./param.string.Sets.the.'irst.4ame ...-, ..public void set'irst4ame(String.string).3 ....!irst4ame.7.string+ ..6 ..,-...-./param.string.sets.the.Last.4ame ...-, ..public void setLast4ame(String.string).3

....last4ame.7.string+ ..6 ..,-...-./ret*rn. D.8et*rns. D ...-, ..public long get d().3 ....return id+ ..6 ..,-...-./param.l.Sets.the. D ...-, ..public void set d(long l).3 ....id.7.l+ ..6 6

Ma$$ing the Contact !b"ect to the +atabase Contact tab#e "he file contact.hb!.1!l is used to !ap 6ontact Ob/ect to the 6ontact table in the database. Here is the code for contact.hb!.1!l0 DE1!l versionFA>.0AEG DH<O6"C+E hibernate.!apping +IB),6 A.88Hibernate8Hibernate :apping <"< 3.088EJA Ahttp088hibernate.sourceforge.net8hibernate.!apping.3.0.dtdAG Dhibernate.!appingG Dclass na!eFAroseindia.tutorial.hibernate.6ontactA tableFA6OJ"76"AG Did na!eFAidA typeFAlongA colu!nFA,<A G Dgenerator classFAassignedA8G D8idG Dproperty na!eFAfirstJa!eAG Dcolu!n na!eFA2,9S"J7:EA 8G D8propertyG Dproperty na!eFAlastJa!eAG Dcolu!n na!eFA)7S"J7:EA8G D8propertyG Dproperty na!eFAe!ailAG Dcolu!n na!eFAE:7,)A8G D8propertyG D8classG D8hibernate.!appingG

Setting .$ MySQL +atabase ,n the configuration file4hibernate.cfg.1!l5 e have specified to use hibernatetutoria# database running on localhost. So, create the databse 4Ahibernatetutoria#-' on the :ySB) server running on localhost. +eve#o$ing Co(e to Test Hibernate e,am$#e Jo e are ready to rite a progra! to insert the data into database. ?e should first understand about the Hibernate@s Session. Hibernate Session is the !ain runti!e interface bet een a Java application and Hibernate. 2irst e are re-uired to get the Hibernate Session.Session2actory allo s application to create the Hibernate Sesssion by reading the configuration fro! hibernate.cfg.1!l file. "hen the save !ethod on session ob/ect is used to save the contact infor!ation to the database0 session%save&contact' Here is the code of 2irstE1a!ple./ava

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.Session'actory+ import org.hibernate.c!g.Con!ig*ration+ ,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.Hibernate.e"ample.to.inset.data.into.Contact.table .-, public class 'irst5"ample.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try3 ......,,.2his.step.)ill.read.hibernate.c!g."ml. and.prepare.hibernate.!or.*se ......Session'actory.session'actory.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ .......session.7session'actory.openSession()+ ........,,Create.ne).instance.o!.Contact.and.set. val*es.in.it.by.reading.them.!rom.!orm.ob<ect .........System.o*t.println(= nserting.8ecord=)+ ........Contact.contact.7.new Contact()+ ........contact.set d(>)+ ........contact.set'irst4ame(=Deepa%=)+ ........contact.setLast4ame(=0*mar=)+ ........contact.set5mail(=deepa%?>@/yahoo.com=)+ ........session.save(contact)+ ........System.o*t.println(=Done=)+

....6catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6finally3 ......,,.(ct*al.contact.insertion.)ill.happen.at.this.step ......session.!l*sh()+ ......session.close()+ ......6 .... ..6 6

,n the ne1t section , ill sho ho to run and test the progra!.

/unning First Hibernate 0%1 2,am$#e


Hibernate is free open source soft are it can be do nload fro! http088 .hibernate.org8#.ht!l. Misit the site and do nload Hibernate 3.0. Cou can do nload the Hibernate and install it yourself. But , have provided very thing in one Lip file. <o nload the e1a!ple code and library fro! here and e1tract the content in your favorite directory say A60Nhibernatee1a!pleA. <o nload file contains the Eclipse pro/ect. "o run the e1a!ple you should have the Eclipse ,<E on your !achine. Start the Eclipse pro/ect and select Java +ro/ect as sho n belo .

6lic3 on AJe1tA button. ,n the ne1t screen leave the output folder as default Ahibernatee1a!ple8binA.

6lic3 on the A2inishA button. Jo Open the 2irstE1a!ple./ava in the editor as sho belo .

6opy contact.hb!.1!l, and hibernate.cfg.1!l in the bin directory of the pro/ect using indo s e1plorer. "o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar as sho n belo .

"his ill run the Hibernate e1a!ple progra! in Eclipse follo ing output ill displayed on the Eclipse 6onsole.

,n this section , sho ed you ho to run the our first Hibernate 3.0 e1a!ple.

.n(erstan(ing Hibernate !*/ Ma$$ing


,n the last e1a!ple e created contact.hb!.1!l to !ap 6ontact Ob/ect to the 6ontact table in the database. Jo let@s understand the each co!ponent of the !apping file. "o recall here is the content of contact.hb!.1!l0 DE1!l versionFA>.0AEG DH<O6"C+E hibernate.!apping +IB),6 A.88Hibernate8Hibernate :apping <"< 3.088EJA Ahttp088hibernate.sourceforge.net8hibernate.!apping.3.0.dtdAG

Dhibernate.!appingG Dclass na!eFAroseindia.tutorial.hibernate.6ontactA tableFA6OJ"76"AG Did na!eFAidA typeFAlongA colu!nFA,<A G Dgenerator classFAassignedA8G D8idG Dproperty na!eFAfirstJa!eAG Dcolu!n na!eFA2,9S"J7:EA 8G D8propertyG Dproperty na!eFAlastJa!eAG Dcolu!n na!eFA)7S"J7:EA8G D8propertyG Dproperty na!eFAe!ailAG Dcolu!n na!eFAE:7,)A8G D8propertyG D8classG D8hibernate.!appingG

Hibernate !apping docu!ents are si!ple 1!l docu!ents. Here are i!portant ele!ents of the !apping file0. >. 3hibernate4ma$$ing5 e#ement "he first or root ele!ent of hibernate !apping docu!ent is Dhibernate.!appingG ele!ent. Bet een the Dhibernate4ma$$ing5 tag class ele!ent4s5 are present. 2. 3c#ass5 e#ement "he D6lassG ele!ent !aps the class ob/ect ith corresponding entity in the database. ,t also tells hat table in the database has to access and hat colu!n in that table it should use. ?ithin one Dhibernate.!appingG ele!ent, several DclassG !appings are possible. 3i(5 e#ement "he DidG ele!ent in uni-ue identifier to identify and ob/ect. ,n fact DidG ele!ent !ap ith the pri!ary 3ey of the table. ,n our code 0 Did na!eFAidA typeFAlongA colu!nFA,<A G pri!ary 3ey !aps to the I+ field of the table C!6TACT. "he attributes of the id ele!ent are0 name "he property na!e used by the persistent class. co#umn "he colu!n used to store the pri!ary 3ey value. ty$e "he Java data type used. unsave(4va#ue "his is the value used to deter!ine if a class has been !ade persistent. ,f the value of the id attribute is null, then it !eans that this ob/ect has not been persisted.

3.

&. 3generator5 e#ement "he 3generator5 !ethod is used to generate the pri!ary 3ey for the ne record. Here is so!e

of the co!!only used generators 0 7 Increment . "his is used to generate pri!ary 3eys of type long, short or int that are uni-ue only. ,t should not be used in the clustered deploy!ent environ!ent. 7 Se)uence . Hibernate can also use the se-uences to generate the pri!ary 3ey. ,t can be used ith <B2, +ostgreSB), Oracle, S7+ <B databases. 7 Assigne( . 7ssigned !ethod is used hen application code generates the pri!ary 3ey. %. 3$ro$erty5 e#ement "he property ele!ents define standard Java attributes and their !apping into database sche!a. "he property ele!ent supports the col*mn child ele!ent to specify additional properties, such as the inde1 na!e on a colu!n or a specific colu!n type.

.n(erstan(ing Hibernate 3generator5 e#ement


,n this lesson you ill learn about hibernate DgeneratorG !ethod in detail. Hibernate generator ele!ent generates the pri!ary 3ey for ne record. "here are !any options provided by the generator !ethod to be used in different situations. The 3generator5 e#ement "his is the optional ele!ent under DidG ele!ent. "he DgeneratorG ele!ent is used to specify the class na!e to be used to generate the pri!ary 3ey for ne record hile saving a ne record. "he Dpara!G ele!ent is used to pass the para!eter 4s5 to the class. Here is the e1a!ple of generator ele!ent fro! our first application0 3generator c#ass8-assigne(-*5 ,n this case DgeneratorG ele!ent do not generate the pri!ary 3ey and it is re-uired to set the pri!ary 3ey value before calling save45 !ethod. Here are the list of so!e co!!only used generators in hibernate0 9enerator +escri$tion ,t generates identifiers of type long, short or int that are uni-ue only hen no other process incre!ent is inserting data into the sa!e table. ,t should not the used in the clustered environ!ent. ,t supports identity colu!ns in <B2, :ySB), :S SB) Server, Sybase and identity HypersonicSB). "he returned identifier is of type long, short or int. "he se-uence generator uses a se-uence in <B2, +ostgreSB), Oracle, S7+ <B, :c=oi or a se-uence generator in ,nterbase. "he returned identifier is of type long, short or int hilo "he hilo generator uses a hi8lo algorith! to efficiently generate identifiers of type long, short or int, given a table and colu!n 4by default hibernateKuni-ueK3ey and ne1tKhi respectively5 as a source of hi values. "he hi8lo algorith! generates identifiers that are uni-ue only for a particular database. <o not use this generator ith connections enlisted

se-hilo uuid guid native assigned select foreign

ith J"7 or ith a user.supplied connection. "he se-hilo generator uses a hi8lo algorith! to efficiently generate identifiers of type long, short or int, given a na!ed database se-uence. "he uuid generator uses a >2$.bit II,< algorith! to generate identifiers of type string, uni-ue ithin a net or3 4the ,+ address is used5. "he II,< is encoded as a string of he1adeci!al digits of length 32. ,t uses a database.generated *I,< string on :S SB) Server and :ySB). ,t pic3s identity, se-uence or hilo depending upon the capabilities of the underlying database. lets the application to assign an identifier to the ob/ect before save45 is called. "his is the default strategy if no DgeneratorG ele!ent is specified. retrieves a pri!ary 3ey assigned by a database trigger by selecting the ro by so!e uni-ue 3ey and retrieving the pri!ary 3ey value. uses the identifier of another associated ob/ect. Isually used in con/unction ith a Done.to. oneG pri!ary 3ey association.

.sing Hibernate 3generator5 to generate i( incrementa##y


7s e have seen in the last section that the incre!ent class generates identifiers of type long, short or int that are uni-ue only hen no other process is inserting data into the sa!e table. ,n this lesson , ill sho you ho to rite running progra! to de!onstrate it. Cou should not use this !ethod to generate the pri!ary 3ey in case of clustured environ!ent. ,n this e ill create a ne table in database, add !appings in the contact.hb!.1!l file, develop the +OJO class 4Boo3./ava5, rite the progra! to test it out. Create Tab#e in the mys)# (atabase Iser the follo ing s-l state!ent to create a ne table in the database. 69E7"E "7B)E Oboo3O 4 OidO int4>>5 JO" JI)) default @0@, Oboo3na!eO varchar4%05 default JI)), +9,:79C =EC 4OidO5 5 "C+EF:y,S7: +eve#o$ing P!:! C#ass &;oo<%"ava' Boo3./ava is our +OJO class hich is to be persisted to the database table Aboo3A.
,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.1ava.Class.to.map.to.the.database.Boo%.table .-, package roseindia.t*torial.hibernate+

public class Boo%.3 ..private long lngBoo% d+ ..private String.strBoo%4ame+ .. ..,-...-./ret*rn.8et*rns.the.lngBoo% d. ...-, ..public long getLngBoo% d().3 ....return lngBoo% d+ ..6 ..,-...-./param.lngBoo% d.2he.lngBoo% d.to.set. ...-, ..public void setLngBoo% d(long lngBoo% d).3 ....this.lngBoo% d.7.lngBoo% d+ ..6 ..,-...-./ret*rn.8et*rns.the.strBoo%4ame. ...-, ..public String.getStrBoo%4ame().3 ....return strBoo%4ame+ ..6 ..,-...-./param.strBoo%4ame.2he.strBoo%4ame.to.set. ...-, ..public void setStrBoo%4ame(String.strBoo%4ame).3 ....this.strBoo%4ame.7.strBoo%4ame+ ..6 6

A((ing Ma$$ing entries to contact%hbm%,m# 7dd the follo ing !apping code into the contact.hb!.1!l file Dclass na!eFAroseindia.tutorial.hibernate.Boo3A tableFAboo3AG Did na!eFAlngBoo3,dA typeFAlongA colu!nFAidA G 3generator c#ass8-increment-*5 D8idG Dproperty na!eFAstrBoo3Ja!eAG Dcolu!n na!eFAboo3na!eA 8G D8propertyG D8classG Jote that e have used increment for the generator class. P7fter adding the entries to the 1!l file copy it to the bin directory of your hibernate eclipse pro/ect4this step is re-uired if you are using eclipse5. Write the c#ient $rogram an( test it out Here is the code of our client progra! to test the application.

,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.5"ample.to.sho).the.increment. class.o!.hibernate. generator.element.to. .-.a*tomatically.generate. the.primay.%ey .-, package roseindia.t*torial.hibernate+ ,,Hibernate. mports import org.hibernate.Session+ import org.hibernate.Session'actory+ import org.hibernate.c!g.Con!ig*ration+ public class d ncrement5"ample.3 ..public static void main (String:;.args).3 ....Session.session.7.null+ ....try3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and. prepare.hibernate.!or.*se ......Session'actory.session'actory.7. new Con!ig*ration().con!ig*re() .b*ildSession'actory()+ ..session.7session'actory.openSession()+ ....... ......org.hibernate.2ransaction.t".7. session.begin2ransaction()+ ....... ......,,Create.ne).instance. o!.Contact.and.set.val*es.in .it.by.reading.them.!rom.!orm.ob<ect .......System.o*t.println(= nserting.Boo%.ob<ect. into.database..=)+ ......Boo%.boo%.7.new Boo%()+ ......boo%.setStrBoo%4ame(=Hibernate. 2*torial=)+ ......session.save(boo%)+ ......System.o*t.println(=Boo%.ob<ect. persisted.to.the.database.=)+ ..........t".commit()+ ..........session.!l*sh()+ ..........session.close()+ ....6catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6finally3 ......6 ....

..6 6

"o test the progra! Select 9un.G9un 7s .G Java 7pplication fro! the eclipse !enu bar. "his ill create a ne record into the boo3 table.

Hibernate .$(ate Query


,n this tutorial e ill sho ho to update a ro ith ne infor!ation by retrieving data fro! the underlying database using the hibernate. )ets first rite a /ava class to update a ro to the database. Create a "ava c#ass Here is the code of our /ava file 4Update5"ample./ava5, here e ill update a field na!e A ns*rance4ame= ith a valueFA1ivan.DharaA fro! a ro of the insurance table. Here is the co(e of (e#ete )uery Update5"ample..<ava.
package roseindia.t*torial.hibernate+ import <ava.*til.Date+ import import import import org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.2ransaction+ org.hibernate.c!g.Con!ig*ration+

public class Update5"ample.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try 3 ......Session'actory.!act.7.new Con!ig*ration() .con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......2ransaction.tr.7.sess.begin2ransaction()+ ...... ns*rance.ins.7.( ns*rance)sess.get ( ns*rance.classB.new Long(C))+ ......ins.set ns*rance4ame(=1ivan.Dhara=)+ ......ins.set nvestement(mo*nt(2DDDD)+ ......ins.set nvestementDate(new Date())+ ......sess.*pdate(ins)+ ......tr.commit()+ ......sess.close()+ ......System.o*t.println(=Update.s*ccess!*llyE=)+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6

..6 6

+o=n#oa( this co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select insurance0K.,< as ,<0K0K, insurance0K.insuranceKna!e as insurance2K0K0K, insurance0K.investedKa!ount as invested3K0K0K, insurance0K.investe!entKdate as investe!&K0K0K fro! insurance insurance0K here insurance0K.,<FE Hibernate0 update insurance set insuranceKna!eFE, investedKa!ountFE, investe!entKdateFE here ,<FE Ipdate successfullyH

Hibernate +e#ete Query


,n this lesson e ill sho ho to delete ro s fro! the underlying database using the hibernate. )ets first rite a /ava class to delete a ro fro! the database. Create a "ava c#ass Here is the code of our /ava file 4DeleteHQL5"ample./ava5, hich e ill delete a ro fro! the insurance table using the -uery =delete.!rom. ns*rance.ins*rance.)here.id.7.2= Here is the co(e of (e#ete )uery DeleteHQL5"ample.<ava.
package roseindia.t*torial.hibernate+ import import import import import org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.2ransaction+ org.hibernate.c!g.Con!ig*ration+

public class DeleteHQL5"ample.3 ..,-.-./a*thor.vinod.0*mar .-. .-.http9,,))).roseindia.net.Hibernate .Criteria.Q*ery.5"ample .-.. .-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b.. ....Session.sess.7.null+ ....try 3 ......Session'actory.!act.7.new

Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.hFl.7.=delete.!rom. ns*rance.ins*rance.)here.id.7.2=+ ......Q*ery.F*ery.7.sess.createQ*ery(hFl)+ ......int ro).7.F*ery.e"ec*teUpdate()+ ......if (ro).77.D)3 ........System.o*t.println(=DoesnG t.deleted.any.ro)E=)+ ......6 ......else3 ........System.o*t.println(=Deleted .8o)9.=.H.ro))+ ......6 ......sess.close()+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

+o=n#oa( this co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 delete fro! insurance here ,<F2 <eleted 9o 0 >

Hibernate Query Language


Hibernate Buery )anguage or HB) for short is e1tre!ely po erful -uery language. HB) is !uch li3e SB) and are case.insensitive, e1cept for the na!es of the Java 6lasses and properties. Hibernate Buery )anguage is used to e1ecute -ueries against database. Hibernate auto!atically generates the s-l -uery and e1ecute it against underlying database if HB) is used in the application. HB) is based on the relational ob/ect !odels and !a3es the SB) ob/ect oriented. Hibernate Buery )anguage uses 6lasses and properties instead of tables and colu!ns. Hibernate Buery )anguage is e1tre!ely po erful and it supports +oly!orphis!, 7ssociations, :uch less verbose than SB). "here are other options that can be used hile using Hibernate. "hese are Query ;y Criteria &Q;C' and Query ;> 2,am$#e &Q;2' using 6riteria 7+, and the 6ative SQL -ueries. ,n this lesson e ill understand HB) in detail.

Why to use HQL?

Fu## su$$ort for re#ationa# o$erations HB) allo s representing SB) -ueries in the for! of ob/ects. Hibernate Buery )anguage uses 6lasses and properties instead of tables and colu!ns. /eturn resu#t as !b"ect "he HB) -ueries return the -uery result4s5 in the for! of ob/ect4s5, hich is easy to use. "his ele!enates the need of creating the ob/ect and populate the data fro! result set. Po#ymor$hic Queries HB) fully supports $o#ymor$hic )ueries. +oly!orphic -ueries results the -uery results along ith all the child ob/ects if any. 2asy to Learn Hibernate Bueries are easy to learn and it can be easily i!ple!ented in the applications. Su$$ort for A(vance features HB) contains !any advance features such as pagination, fetch /oin ith dyna!ic profiling, ,nner8outer8full /oins, 6artesian products. ,t also supports +ro/ection, 7ggregation 4!a1, avg5 and grouping, Ordering, Sub -ueries and SB) function calls. +atabase in(e$en(ent Bueries ritten in HB) are database independent 4,f database supports the underlying feature5.

.n(erstan(ing HQL Synta, 7ny Hibernate Buery )anguage !ay consist of follo ing ele!ents0

6lauses 7ggregate functions Sub-ueries

C#auses in the HQL are


from se#ect =here or(er by grou$ by

Aggregate functions are


avg&%%%', sum&%%%', min&%%%', ma,&%%%' count&7' count4...5, count4distinct ...5, count4all...5

Sub)ueries Sub-ueries are nothing but its a -uery ithin another -uery. Hibernate supports Sub-ueries if the underlying database supports it.

Pre$aring tab#e for HQL 2,am$#es


,n this lesson e ill create insurance table and populate it ith the data. ?e ill use insurance table for rest of the HB) tutorial. "o create the insurance table and insert the sa!ple data, run the follo ing s-l -uery0

,-2able.str*ct*re.!or.table.Iins*ranceI.-, drop.table.i!.e"ists.Iins*ranceI+ C85(25.2(BL5.Iins*ranceI.( ..I DI.int(CC).4O2.4ULL.de!a*lt.GDGB ..Iins*rance?nameI.varchar(JD).de!a*lt.4ULLB ..Iinvested?amo*ntI.int(CC).de!a*lt.4ULLB ..Iinvestement?dateI.datetime.de!a*lt.4ULLB ..#8 $(8K.05K..(I DI) ).2K#57$y S($+ ,-Data.!or.the.table.Iins*ranceI.-, insert.into.Iins*ranceI.val*es. (CBGCar. ns*ranceGBCDDDBG2DDJADCADJ.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (2BGLi!e. ns*ranceGBCDDBG2DDJACDADC.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (>BGLi!e. ns*ranceGBJDDBG2DDJACDACJ.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (LBGCar. ns*ranceGB2JDDBG2DDJADCADC.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (JBGDental. ns*ranceGBJDDBG2DDLADCADC.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es .(MBGLi!e. ns*ranceGB&DDBG2DD>ADCADC.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (NBG2ravel. ns*ranceGB2DDDBG2DDJAD2AD2.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (@BG2ravel. ns*ranceGBMDDBG2DDJAD>AD>.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (&BG$edical. ns*ranceGBNDDBG2DDJADLADL.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (CDBG$edical. ns*ranceGB&DDBG2DDJAD>AD>.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (CCBGHome. ns*ranceGB@DDBG2DDJAD2AD2.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (C2BGHome. ns*ranceGBNJDBG2DDLAD&AD&.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es.

(C>BG$otorcycle. ns*ranceGB&DDB G2DDLADMADM.DD9DD9DDG)+ insert.into.Iins*ranceI.val*es. (CLBG$otorcycle. ns*ranceGBN@D BG2DDJAD>AD>.DD9DD9DDG)+

7bove S-l -uery ill create insurance table and add the follo ing data0 I+ insurance?name > 6ar ,nsurance 2 )ife ,nsurance 3 )ife ,nsurance & 6ar ,nsurance % <ental ,nsurance # )ife ,nsurance ( "ravel ,nsurance $ "ravel ,nsurance ' :edical ,nsurance >0 :edical ,nsurance >> Ho!e ,nsurance >2 Ho!e ,nsurance investe(?amount investement?(ate >000 >00 %00 2%00 %00 '00 2000 #00 (00 '00 $00 (%0 200%.0>.0% 00000000 200%.>0.0> 00000000 200%.>0.>% 00000000 200%.0>.0> 00000000 200&.0>.0> 00000000 2003.0>.0> 00000000 200%.02.02 00000000 200%.03.03 00000000 200%.0&.0& 00000000 200%.03.03 00000000 200%.02.02 00000000 200&.0'.0' 00000000 200&.0#.0# 00000000 200%.03.03 00000000

>3 :otorcycle ,nsurance '00 >& :otorcycle ,nsurance ($0

,n the future lessons e ill use this table to rite different HB) e1a!ples.

Writing !/M for Insurance tab#e


,n this lesson e ill rite the /ava class and add necessary code in the contact.hb!.1!l file. Create P!:! c#ass Here is the code of our /ava file 4,nsurance./ava5, hich e ill !ap to the insurance table.

package roseindia.t*torial.hibernate+ import <ava.*til.Date+ ,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net

.-.1ava.Class.to.map.to.the.database.ins*rance.table .-, public class ns*rance.3 ..private long lng ns*rance d+ ..private String.ins*rance4ame+ ..private int investement(mo*nt+ ..private Date.investementDate+ .. ..,-...-./ret*rn.8et*rns.the.ins*rance4ame. ...-, ..public String.get ns*rance4ame().3 ....return ins*rance4ame+ ..6 ..,-...-./param.ins*rance4ame.2he.ins*rance4ame.to.set. ...-, ..public void set ns*rance4ame(String.ins*rance4ame).3 ....this.ins*rance4ame.7.ins*rance4ame+ ..6 ..,-...-./ret*rn.8et*rns.the.investement(mo*nt. ...-, ..public int get nvestement(mo*nt().3 ....return investement(mo*nt+ ..6 ..,-...-./param.investement(mo*nt.2he.investement(mo*nt .to.set. ...-, ..public void set nvestement(mo*nt(int investement(mo*nt) .3 ....this.investement(mo*nt.7.investement(mo*nt+ ..6 ..,-...-./ret*rn.8et*rns.the.investementDate. ...-, ..public Date.get nvestementDate().3 ....return investementDate+ ..6 ..,-...-./param.investementDate.2he.investementDate.to.set. ...-, ..public void set nvestementDate(Date.investementDate).3 ....this.investementDate.7.investementDate+ ..6 ..,-...-./ret*rn.8et*rns.the.lng ns*rance d. ...-, ..public long getLng ns*rance d().3 ....return lng ns*rance d+ ..6 ..,-...-./param.lng ns*rance d.2he.lng ns*rance d.to.set.

...-, ..public void setLng ns*rance d(long lng ns*rance d).3 ....this.lng ns*rance d.7.lng ns*rance d+ ..6 6

A((ing ma$$ings into contact%hbm%,m# fi#e 7dd the follo ing code into contact.hb!.1!l file.
.Oclass.name7=roseindia.t*torial.hibernate. ns*rance=.table7=ins*rance=P Oid.name7=lng ns*rance d=.type7=long=.col*mn7= D=.P Ogenerator.class7=increment=,P O,idP Oproperty.name7=ins*rance4ame=P Ocol*mn.name7=ins*rance?name=.,P O,propertyP Oproperty.name7=investement(mo*nt=P Ocol*mn.name7=invested?amo*nt=.,P O,propertyP Oproperty.name7=investementDate=P Ocol*mn.name7=investement?date=.,P O,propertyP O,classP ..... ......

Jo

e have created the +OJO class and necessary !apping into contact.hb!.1!l file.

HQL from c#ause 2,am$#e


,n this e1a!ple you ill learn ho to use the HB) fro! clause. "he fro! clause is the si!plest possible Hibernate Buery. E1a!ple of fro! clause is0 fro! ,nsurance insurance Here is the full code of the fro! clause e1a!ple0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+

import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.Select.HQL.5"ample .-, public class SelectHQL5"ample.3 ..public static void main(String:;.args).3 ..Session.session.7.null+ ..try3 ....,,.2his.step.)ill.read.hibernate.c!g."ml .and.prepare.hibernate.!or.*se ....Session'actory.session'actory.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ .....session.7session'actory.openSession()+ ..... ..... .,,Using.!rom.Cla*se ..String.SQL?QU58K.7=!rom. ns*rance.ins*rance=+ ..Q*ery.F*ery.7.session.createQ*ery(SQL?QU58K)+ ..for( terator.it7F*ery.iterate()+it.has4e"t()+)3 ns*rance.ins*rance7( ns*rance)it.ne"t()+ .System.o*t.println(= D9.=.H. ins*rance.getLng ns*rance d())+ ...System.o*t.println(='irst .4ame9.=.H.ins*rance.get ns*rance4ame())+ ...6 . ....session.close()+ 6catch(5"ception.e)3 ....System.o*t.println(e.get$essage())+ 6finally3 ....6 ..6.. 6

"o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar. 2ollo ing out is displayed in the Eclipse console0
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select insurance0K.,< as colK0K0K fro! insurance insurance0K ,<0 > Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K,

insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 6ar ,nsurance ,<0 2 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 )ife ,nsurance ,<0 3 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 )ife ,nsurance ,<0 & Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 6ar ,nsurance ,<0 % Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 <ental ,nsurance ,<0 # Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 )ife ,nsurance ,<0 ( Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE

2irst Ja!e0 "ravel ,nsurance ,<0 $ Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 "ravel ,nsurance ,<0 ' Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 :edical ,nsurance ,<0 >0 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 :edical ,nsurance ,<0 >> Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 Ho!e ,nsurance ,<0 >2 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 Ho!e ,nsurance ,<0 >3 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 :otorcycle ,nsurance

,<0 >& Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE 2irst Ja!e0 :otorcycle ,nsurance

Hibernate Se#ect C#ause


,n this lesson e ill rite e1a!ple code to select the data fro! ,nsurance table using Hibernate Select 6lause. "he select clause pic3s up ob/ects and properties to return in the -uery result set. Here is the -uery0 Select insurance.lng,nsurance,d, insurance.insuranceJa!e, insurance.investe!ent7!ount, insurance.investe!ent<ate fro! ,nsurance insurance hich selects all the ro s 4insurance%#ngInsuranceI(@ insurance%insurance6ame@ insurance%investementAmount@ insurance%investement+ate5 fro! ,nsurance table. Hibernate generates the necessary s-l -uery and selects all the records fro! ,nsurance table. Here is the code of our /ava file hich sho s ho select HB) can be used0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.HQL.Select.Cla*se.5"ample .-, public class SelectCla*se5"ample.3 ..public static void main(String:;.args).3 ..Session.session.7.null+ ..try3 ....,,.2his.step.)ill.read.hibernate.c!g."ml. and.prepare.hibernate.!or.*se ....Session'actory.session'actory.7.new Con!ig*ration().con!ig*re()

.b*ildSession'actory()+ ....session.7session'actory.openSession()+ ..... ....,,Create.Select.Cla*se.HQL .....String.SQL?QU58K.7=Select.ins*rance. lng ns*rance dBins*rance.ins*rance4ameB=.H. .....=ins*rance.investement(mo*ntBins*rance. investementDate.!rom. ns*rance.ins*rance=+ .Q*ery.F*ery.7.session.createQ*ery(SQL?QU58K)+ .for( terator.it7F*ery.iterate()+it.has4e"t()+)3 .......Ob<ect:;.ro).7.(Ob<ect:;).it.ne"t()+ .......System.o*t.println(= D9.=.H.ro):D;)+ .......System.o*t.println(=4ame9.=.H.ro):C;)+ .......System.o*t.println(=(mo*nt9.=.H.ro):2;)+ .....6 ..... ........session.close()+ ..6catch(5"ception.e)3 ....System.o*t.println(e.get$essage())+ ..6finally3 ....6 ..6 6

"o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar. 2ollo ing out is displayed in the Eclipse console0
Hibernate0 select insurance0K.,< as colK0K0K, insurance0K.insuranceKna!e as colK>K0K, insurance0K.investedKa!ount as colK2K0K, insurance0K.investe!entKdate as colK3K0K fro! insurance insurance0K ,<0 > Ja!e0 6ar ,nsurance 7!ount0 >000 ,<0 2 Ja!e0 )ife ,nsurance 7!ount0 >00 ,<0 3 Ja!e0 )ife ,nsurance 7!ount0 %00

,<0 & Ja!e0 6ar ,nsurance 7!ount0 2%00 ,<0 % Ja!e0 <ental ,nsurance 7!ount0 %00 ,<0 # Ja!e0 )ife ,nsurance 7!ount0 '00 ,<0 ( Ja!e0 "ravel ,nsurance 7!ount0 2000 ,<0 $ Ja!e0 "ravel ,nsurance 7!ount0 #00 ,<0 ' Ja!e0 :edical ,nsurance 7!ount0 (00 ,<0 >0 Ja!e0 :edical ,nsurance 7!ount0 '00 ,<0 >> Ja!e0 Ho!e ,nsurance 7!ount0 $00

,<0 >2 Ja!e0 Ho!e ,nsurance 7!ount0 (%0 ,<0 >3 Ja!e0 :otorcycle ,nsurance 7!ount0 '00 ,<0 >& Ja!e0 :otorcycle ,nsurance 7!ount0 ($0

Hibernate Count Query


In this section we will show you, how to use the Count Query. Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return an aggregate value (such as sum, average, and count calculated from property values of all ob!ects satisfying other query criteria. "hese functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and all values (e#cept null values , respectively. $ollowing is a list of aggregate functions with their respective synta#% all of them are self& e#planatory. count( ' distinct ( all ) ob!ect ( ob!ect.property count(*) (equivalent to count(all ...), counts null values also

sum ( ' distinct ( all ) ob!ect.property avg( ' distinct ( all ) ob!ect.property max( ' distinct ( all ) ob!ect.property min( ' distinct ( all ) ob!ect.property

Here is the /ava code for counting the records fro! insurance table0
package roseindia.t*torial.hibernate+ import <ava.*til. terator+ import <ava.*til.List+ import org.hibernate.Q*ery+ import org.hibernate.Session+

import org.hibernate.Session'actory+ import org.hibernate.2ransaction+ import org.hibernate.c!g.Con!ig*ration+ public class HibernateHQLCo*nt'*nctions.3 ..,-...-. ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....int co*nt.7.D+ ....try 3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re() .b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.SQL?QU58K.7.=select. co*nt(-)!rom. ns*rance.ins*rance.gro*p.by. ins*rance.lng ns*rance d=+ ........Q*ery.F*ery.7. sess.createQ*ery(SQL?QU58K)+ ........for ( terator.it. 7.F*ery.iterate()+.it.has4e"t()+).3 ..........it.ne"t()+ ............co*ntHH+ ........6 ........System.o*t.println(= 2otal.ro)s9.=.H.co*nt)+ ......sess.close()+ ....6 ....catch(5"ception.e)3 ......System.o*t.println (e.get$essage())+ ....6 ..6 6

+o=n#oa( this co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select count4P5 as colK0K0K fro! insurance insurance0K group by insurance0K.,< "otal ro s0 #

Hibernate Avg&' Function &Aggregate Functions'


,n this section, e ill sho you, ho to use the avg45 function. Hibernate supports !ultiple aggregate functions. ?hen they are used in HB) -ueries, they return an aggregate value 4 such as avg(... , sum(... , min(... , ma#(... , count(* , count(... , count(distinct ... , count(all... 5 calculated fro! property values of all ob/ects satisfying other -uery criteria. 2ollo ing is a aggregate function 4avg45 function5 ith their respective synta1.
avg( ' distinct ( all ) ob!ect.property +

"he avg&' function aggregates the average value of the given colu!n. Tab#e 6ame insurance ,< insuranceKna!e investedKa!ount investe!entKdate 2 > 3 & % # ( )ife ,nsurance *ivan <hara )ife ,nsurance 6ar ,nsurance <ental ,nsurance )ife ,nsurance 2%000 20000 %00 2%00 %00 '00 0000.00.00 00000000 200(.0(.30 >(02'00% 200%.>0.>% 00000000 200%.0>.0> 00000000 200&.0>.0> 00000000 2003.0>.0> 00000000 200%.02.02 00000000

"ravel ,nsurance 2000

Here is the /ava code to retrieve the average value of AinvestedKa!ountA colu!n fro! insurance table0
package roseindia.t*torial.hibernate+ import <ava.*til. terator+ import <ava.*til.List+ import import import import org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+

public class HibernateHQL(vg'*nction.3

..,-...-./Qinod.%*mar ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try 3 ......Session'actory.!act.7.new Con!ig*ration() .con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.SQL?QU58K.7.=select.avg (investement(mo*nt).!rom. ns*rance.ins*rance=+ ......Q*ery.F*ery.7.sess.createQ*ery(SQL?QU58K)+ ......List.list.7.F*ery.list()+ ......System.o*t.println(=(verage.o!. nvested.(mo*nt9.=.H.list.get(D))+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

+o=n#oa( this Co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select avg4insurance0K.investedKa!ount5 as colK0K0K fro! insurance insurance0K 7verage of ,nvested 7!ount0 (3&2.$%(>

Hibernate Min&' Function &Aggregate Functions'


,n this section, e ill sho you, ho to use the :in45 function. Hibernate supports !ultiple aggregate functions. ?hen they are used in HB) -ueries, they return an aggregate value 4 such as avg(... , sum(... , min(... , ma#(... , count(* , count(... , count(distinct ... , count(all... 5 calculated fro! property values of all ob/ects satisfying other -uery criteria. 2ollo ing is a aggregate function 4!in45 function5 ith their respective synta1.
min( ' distinct ( all ) ob!ect.property

"he Min&' function aggregates the !ini!u! value of the given colu!n.

Tab#e 6ame insurance ,< insuranceKna!e investedKa!ount investe!entKdate 2 > 3 & % # ( )ife ,nsurance *ivan <hara )ife ,nsurance 6ar ,nsurance <ental ,nsurance )ife ,nsurance 2%000 20000 %00 2%00 %00 '00 0000.00.00 00000000 200(.0(.30 >(02'00% 200%.>0.>% 00000000 200%.0>.0> 00000000 200&.0>.0> 00000000 2003.0>.0> 00000000 200%.02.02 00000000

"ravel ,nsurance 2000

Here is the /ava code to retrieve the !ini!u! value of AinvestedKa!ountA colu!n fro! insurance table0
package roseindia.t*torial.hibernate+ import <ava.*til.List+ import import import import org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+

public class HibernateHQL$in'*nction.3 ..,-...-./Qinod.0*mar ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try 3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.SQL?QU58K.7.=select.min (investement(mo*nt).!rom. ns*rance.ins*rance=+ ......Q*ery.F*ery.7.sess.createQ*ery(SQL?QU58K)+ ......List.list.7.F*ery.list()+ ......System.o*t.println(=$in. nvested.(mo*nt9.=.H.list.get(D))+ ....6 ....catch(5"ception.e)3

......System.o*t.println(e.get$essage())+ ....6 ..6 6

+o=n#oa( this Co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select !in4insurance0K.investedKa!ount5 as colK0K0K fro! insurance insurance0K :in ,nvested 7!ount0 %00

HQL Where C#ause 2,am$#e


?here 6lause is used to li!it the results returned fro! database. ,t can be used ith aliases and if the aliases are not present in the Buery, the properties can be referred by na!e. 2or e1a!ple0
fro! ,nsurance here lng,nsurance,dF@>@

?here 6lause can be used ith or ithout Select 6lause. Here the e1a!ple code0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar ..-.http9,,))).roseindia.net .-.HQL.Rhere.Cla*se.5"ample .-.Rhere.Cla*se.Rith.Select.Cla*se.5"ample .-, public class RhereCla*se5"ample.3 ..public static void main(String:;.args).3 ..Session.session.7.null+

..try3 ....,,.2his.step.)ill.read.hibernate.c!g. "ml.and.prepare.hibernate.!or.*se ....Session'actory.session'actory.7.new Con!ig*ration().con!ig*re(). b*ildSession'actory()+ ....session.7session'actory.openSession()+ ..... ......System.o*t.println(=------------------------------=)+ ......System.o*t.println(=Q*ery.*sing. Hibernate.Q*ery.Lang*age=)+ ....,,Q*ery.*sing.Hibernate.Q*ery.Lang*age .....String.SQL?QU58K.7=.!rom. ns*rance .as.ins*rance.)here.ins*rance. lng ns*rance d7GCG=+ .....Q*ery.F*ery.7.session.createQ*ery (SQL?QU58K)+ .....for( terator.it7F*ery.iterate() +it.has4e"t()+)3 ....... ns*rance.ins*rance7( ns*rance)it .ne"t()+ .......System.o*t.println(= D9.=.H.ins*rance. getLng ns*rance d())+ .......System.o*t.println(=4ame9.=. H.ins*rance..get ns*rance4ame())+ ....... .....6 .....System.o*t.println(=------------------------------=)+ .....System.o*t.println(=Rhere.Cla*se.Rith .Select.Cla*se=)+ ....,,Rhere.Cla*se.Rith.Select.Cla*se .....SQL?QU58K.7=Select.ins*rance. lng ns*rance dBins*rance.ins*rance4ameB=.H .....=ins*rance.investement(mo*ntB ins*rance.investementDate.!rom. ns*rance .ins*rance.=H.=.)here.ins*rance. lng ns*rance d7GCG=+ .....F*ery.7.session.createQ*ery(SQL?QU58K)+ .....for( terator.it7F*ery.iterate()+it. has4e"t()+)3 .......Ob<ect:;.ro).7.(Ob<ect:;).it.ne"t()+ .......System.o*t.println(= D9.=.H.ro):D;)+ .......System.o*t.println(=4ame9.=.H.ro):C;)+ ....... .....6 .....System.o*t.println(=------------------------------=)+ ........session.close()+ ..6catch(5"ception.e)3 ....System.o*t.println(e.get$essage())+ ..6finally3 ....6.... ..6

"o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar. 2ollo ing out is displayed in the Eclipse console0
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP Buery using Hibernate Buery )anguage Hibernate0 select insurance0K.,< as colK0K0K fro! insurance insurance0K here 4insurance0K.,<F@>@5 ,<0 > Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 6ar ,nsurance PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP ?here 6lause ?ith Select 6lause Hibernate0 select insurance0K.,< as colK0K0K, insurance0K.insuranceKna!e as colK>K0K, insurance0K.investedKa!ount as colK2K0K, insurance0K.investe!entKdate as colK3K0K fro! insurance insurance0K here 4insurance0K.,<F@>@5 ,<0 > Ja!e0 6ar ,nsurance PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

HQL 9rou$ ;y C#ause 2,am$#e


*roup by clause is used to return the aggregate values by grouping on returned co!ponent. HB) supports *roup By 6lause. ,n our e1a!ple e ill calculate the su! of invested a!ount in each insurance type. Here is the /ava code for calculating the invested a!ount insurance ise0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar .-. .-.http9,,))).roseindia.net.

HQL.Sro*p.by.Cla*se.5"ample .-.. .-, public class HQLSro*pBy5"ample.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try 3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and.prepare.hibernate.!or ......,,.*se ......Session'actory.session'actory.7. new Con!ig*ration().con!ig*re() ...........b*ildSession'actory()+ ......session.7.session'actory.openSession()+ ......,,Sro*p.By.Cla*se.5"ample ......String.SQL?QU58K.7.=select.s*m (ins*rance.investement(mo*nt)B ins*rance.ins*rance4ame.= ..........H.=!rom. ns*rance.ins*rance. gro*p.by.ins*rance.ins*rance4ame=+ .Q*ery.F*ery.7.session.createQ*ery(SQL?QU58K)+ .for ( terator.it.7. F*ery.iterate()+.it.has4e"t()+).3 .Ob<ect:;.ro).7.(Ob<ect:;).it.ne"t()+ .System.o*t.println(= nvested.(mo*nt9.=.H.ro):D;)+ .System.o*t.println(= ns*rance.4ame9.=.H.ro):C;)+ ......6 ......session.close()+ ....6.catch (5"ception.e).3 ......System.o*t.println(e.get$essage())+ ....6.finally 3 ....6 ..6 6

"o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar. 2ollo ing out is displayed in the Eclipse console0
Hibernate0 select su!4insurance0K.investedKa!ount5 as colK0K0K, insurance0K.insuranceKna!e as colK>K0K fro! insurance insurance0K group by insurance0K.insuranceKna!e ,nvested 7!ount0 3%00 ,nsurance Ja!e0 6ar ,nsurance ,nvested 7!ount0 %00 ,nsurance Ja!e0 <ental ,nsurance

,nvested 7!ount0 >%%0 ,nsurance Ja!e0 Ho!e ,nsurance ,nvested 7!ount0 >%00 ,nsurance Ja!e0 )ife ,nsurance ,nvested 7!ount0 >#00 ,nsurance Ja!e0 :edical ,nsurance ,nvested 7!ount0 >#$0 ,nsurance Ja!e0 :otorcycle ,nsurance ,nvested 7!ount0 2#00 ,nsurance Ja!e0 "ravel ,nsurance

HQL !r(er ;y 2,am$#e


Order by clause is used to retrieve the data fro! database in the sorted order by any property of returned class or co!ponents. HB) supports Order By 6lause. ,n our e1a!ple e ill retrieve the data sorted on the insurance type. Here is the /ava e1a!ple code0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar .-. .-.http9,,))).roseindia.net.HQL.Order.by.Cla*se.5"ample .-.. .-, public class HQLOrderBy5"ample.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try 3 ......,,.2his.step.)ill.read.hibernate. c!g."ml.and.prepare.hibernate.!or ......,,.*se ......Session'actory.session'actory.7 .new Con!ig*ration().con!ig*re() ...........b*ildSession'actory()+ ......session.7.session'actory.openSession()+ ......,,Order.By.5"ample

......String.SQL?QU58K.7.=.!rom. ns*rance.as. ins*rance.order.by.ins*rance.ins*rance4ame=+ ......Q*ery.F*ery.7. session.createQ*ery(SQL?QU58K)+ ......for ( terator.it. 7.F*ery.iterate()+.it.has4e"t()+).3 ........ ns*rance.ins*rance.7.( ns*rance).it.ne"t()+ ........System.o*t.println(= D9.=.H.ins*rance. getLng ns*rance d())+ ........System.o*t.println(=4ame9.=.H. ins*rance.get ns*rance4ame())+ ......6 ......session.close()+ ....6.catch (5"ception.e).3 ......System.o*t.println(e.get$essage())+ ....6.finally 3 ....6 ..6 6

"o run the e1a!ple select 9un.G 9un 7s .G Java 7pplication fro! the !enu bar. 2ollo ing out is displayed in the Eclipse console0
Hibernate0 select insurance0K.,< as colK0K0K fro! insurance insurance0K order by insurance0K.insuranceKna!e ,<0 > Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 6ar ,nsurance ,<0 & Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 6ar ,nsurance ,<0 % Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 <ental ,nsurance ,<0 >>

Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 Ho!e ,nsurance ,<0 >2 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 Ho!e ,nsurance ,<0 2 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 )ife ,nsurance ,<0 3 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 )ife ,nsurance ,<0 # Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 )ife ,nsurance ,<0 ' Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 :edical ,nsurance ,<0 >0 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro!

insurance insurance0K here insurance0K.,<FE Ja!e0 :edical ,nsurance ,<0 >3 Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 :otorcycle ,nsurance ,<0 >& Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 :otorcycle ,nsurance ,<0 ( Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 "ravel ,nsurance ,<0 $ Hibernate0 select insurance0K.,< as ,<0K, insurance0K.insuranceKna!e as insurance2K2K0K, insurance0K.investedKa!ount as invested3K2K0K, insurance0K.investe!entKdate as investe!&K2K0K fro! insurance insurance0K here insurance0K.,<FE Ja!e0 "ravel ,nsurance

Hibernate Criteria Query 2,am$#e


"he 6riteria interface allo s to create and e1ecute ob/ect.oriented -ueries. ,t is po erful alternative to the HB) but has o n li!itations. 6riteria Buery is used !ostly in case of !ulti criteria search screens, here HB) is not very effective. "he interface org.hibernate.6riteria is used to create the criterion for the search. "he org.hibernate.6riteria interface represents a -uery against a persistent class. "he Session is a factory for 6riteria instances. Here is a si!ple e1a!ple of Hibernate 6riterial Buery0

package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar .-. .-.http9,,))).roseindia.net. Hibernate.Criteria.Q*ery.5"ample .-.. .-,public class HibernateCriteriaQ*ery5"ample.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try 3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and.prepare.hibernate.!or ......,,.*se ......Session'actory. session'actory.7.new Con!ig*ration().con!ig*re() ...........b*ildSession'actory()+ ......session.7. session'actory.openSession()+ ......,,Criteria.Q*ery.5"ample ......Criteria.crit.7. session.createCriteria( ns*rance.class)+ ......List.ins*rances.7. crit.list()+ ......for( terator.it.7. ins*rances.iterator()+it.has4e"t()+)3 ........ ns*rance.ins*rance.7. ( ns*rance).it.ne"t()+ ........System.o*t.println(= D9.=.H.ins*rance.getLng ns*rance d())+ ........System.o*t.println(= 4ame9.=.H.ins*rance.get ns*rance4ame())+ ........ ......6 ......session.close()+ ....6.catch (5"ception.e).3 ......System.o*t.println(e.get$essage())+ ....6.finally 3 ....6.... ..6 6

"he above 6riteria Buery e1a!ple selects all the records fro! the table and displays on the console. ,n the above code the follo ing code creates a ne Criteria instance, for the class Insurance0 6riteria crit F session.create6riteria4,nsurance.class5Q "he code0

)ist insurances F crit.list45Q creates the s-l -uery and e1ecute against database to retrieve the data.

Criteria Query 2,am$#es


,n the last lesson e learnt ho to use 6riteria Buery to select all the records fro! ,nsurance table. ,n this lesson e ill learn ho to restrict the results returned fro! the database. <ifferent !ethod provided by 6riteria interface can be used ith the help of 9estrictions to restrict the records fetched fro! database. Criteria Interface $rovi(es the fo##o=ing metho(s Metho( add addOrder create7lias create6riteria set2etchSiLe set2irst9esult set:a19esults uni-ue9esult +escri$tion "he 7dd !ethod adds a 6riterion to constrain the results to be retrieved. 7dd an Order to the result set. Join an association, assigning an alias to the /oined entity "his !ethod is used to create a ne 6riteria, ArootedA at the associated entity. "his !ethod is used to set a fetch siLe for the underlying J<B6 -uery. "his !ethod is used to set the first result to be retrieved. "his !ethod is used to set a li!it upon the nu!ber of ob/ects to be retrieved. "his !ethod is used to instruct the Hibernate to fetch and return the uni-ue records fro! database.

6lass 9estriction provides built.in criterion via static factory !ethods. ,!portant !ethods of the 9estriction class are0 Metho( 9estriction.allEq 9estriction.between 9estriction.eq 9estriction.ge 9estriction.gt +escri$tion "his is used to apply an Ae-ualsA constraint to each property in the 3ey set of a $ap "his is used to apply a Abet eenA constraint to the na!ed property "his is used to apply an Ae-ualA constraint to the na!ed property "his is used to apply a Agreater than or e-ualA constraint to the na!ed property "his is used to apply a Agreater thanA constraint to the na!ed

9estriction.idEq 9estriction.ilike 9estriction.in 9estriction.isNotNull 9estriction.isNull 9estriction.le 9estriction.like 9estriction.lt 9estriction.ltProperty 9estriction.ne 9estriction.neProperty 9estriction.not 9estriction.or

property "his is used to apply an Ae-ualA constraint to the identifier property "his is case.insensitive Ali3eA, si!ilar to +ostgres ili%e operator "his is used to apply an AinA constraint to the na!ed property "his is used to apply an Ais not nullA constraint to the na!ed property "his is used to apply an Ais nullA constraint to the na!ed property "his is used to apply a Aless than or e-ualA constraint to the na!ed property "his is used to apply a Ali3eA constraint to the na!ed property "his is used to apply a Aless thanA constraint to the na!ed property "his is used to apply a Aless thanA constraint to t o properties "his is used to apply a Anot e-ualA constraint to the na!ed property "his is used to apply a Anot e-ualA constraint to t o properties "his returns the negation of an e1pression "his returns the dis/uction of t o e1pressions

Here is an e1a!ple code that sho s ho to use 8estrictions.li%e.method.and.restrict.the.

ma"im*m.ro)s.ret*rned.by.F*ery.by.setting.the.Criteria.set$a"8es*lts().val*e.to.J. package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.criterion.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar .-. .-.http9,,))).roseindia.net. Hibernate.Criteria.Q*ery.5"ample .-.. .-,public class HibernateCriteriaQ*ery5"ample2.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try 3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and.prepare.hibernate.!or ......,,.*se

......Session'actory.session'actory .7.new Con!ig*ration().con!ig*re() ...........b*ildSession'actory()+ ......session.7. session'actory.openSession()+ ......,,Criteria.Q*ery.5"ample ......Criteria.crit.7. session.createCriteria( ns*rance.class)+ ......crit.add(8estrictions.li%e(= ins*rance4ame=B.=TaT=))+.,,Li%e.condition ......crit.set$a"8es*lts(J)+.,, 8estricts.the.ma".ro)s.to.J ......List.ins*rances.7.crit.list()+ ......for( terator.it.7. ins*rances.iterator()+it.has4e"t()+)3 ........ ns*rance.ins*rance.7 .( ns*rance).it.ne"t()+ ........System.o*t.println(= D9.=.H.ins*rance.getLng ns*rance d())+ ........System.o*t.println(= 4ame9.=.H.ins*rance.get ns*rance4ame())+ ........ ......6 ......session.close()+ ....6.catch (5"ception.e).3 ......System.o*t.println(e.get$essage())+ ....6.finally 3 ....6.... ..6 6

HibernateAs ;ui#t4in criterion ;et=een &using Integer'


,n this tutorial,, you ill learn to use Abet eenA ith the ,nteger class. ABet eenA hen used ith the ,nteger ob/ect, ,t ta3es three para!eters e.g. bet)een(=property?name=Bmin?intBma"?int). 9estriction class provides built.in criterion via static factory !ethods. One i!portant !ethod of the 9estriction class is between : )hich.is.*sed.to.apply.a.=bet)een=.constraint.to.the.named.
property

Here is the co(e of the c#ass using -bet=een- =ith the Integer c#ass
package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.criterion.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.vinod.0*mar .-.

.-.http9,,))).roseindia.net. Hibernate.Criteria.Q*ery.5"ample .-.. .-,public class HibernateCriteriaQ*eryBet)een2)o nteger.3 ..public static void main(String:;.args).3 ....Session.session.7.null+ ....try 3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and.prepare.hibernate.!or ......,,.*se ......Session'actory. session'actory.7.new Con!ig*ration().con!ig*re() ...........b*ildSession'actory()+ ......session.7. session'actory.openSession()+ ......,,Criteria.Q*ery.5"ample ......Criteria.crit.7. session.createCriteria( ns*rance.class)+ ......crit.add(5"pression.bet)een(= investement(mo*nt=B.new nteger(CDDD)B ...............new nteger(2JDD)))+.,, Bet)een.condition ......crit.set$a"8es*lts(J)+.,, 8estricts.the.ma".ro)s.to.J ......List.ins*rances.7.crit.list()+ ......for( terator.it.7. ins*rances.iterator()+it.has4e"t()+)3 ........ ns*rance.ins*rance.7 .( ns*rance).it.ne"t()+ ........System.o*t.println(= D9.=.H.ins*rance.getLng ns*rance d())+ ........System.o*t.println(= 4ame9.=.H.ins*rance.get ns*rance4ame())+ ........System.o*t.println(= (mo*nt9.=.H.ins*rance.get nvestement(mo*nt())+ ........ ......6 ......session.close()+ ....6.catch (5"ception.e).3 ......System.o*t.println(e.get$essage())+ ....6.finally 3 ....6.... ..6 6

+o=n#oa( this co(e !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly.

Hibernate0 select thisK.,< as ,<0K0K, thisK.insuranceKna!e as insurance2K0K0K, thisK.investedKa!ount as invested3K0K0K, thisK.investe!entKdate as investe!&K0K0K fro! insurance thisK here thisK.investedKa!ount bet een E and E li!it E ,<0 > Ja!e0 6ar ,nsurance 7!ount0 >000 ,<0 & Ja!e0 6ar ,nsurance 7!ount0 2%00 ,<0 ( Ja!e0 "ravel ,nsurance 7!ount0 2000

Hibernate 6ative SQL 2,am$#e


6ative SQL is hand ritten SB) for all database operations li3e create, update, delete and select. Hibernate 6ative Query also supports stored procedures. Hibernate allo s you to run Jative SB) Buery for all the database operations, so you can use your e1isting hand ritten s-l ith Hibernate, this also helps you in !igrating your SB)8J<B6 based application to Hibernate. ,n this e1a!ple e ill sho you ho you can use Jative SB) ith hibernate. Cou ill learn ho to use Jative to calculate average and then in another e1a!ple select all the ob/ects fro! table. Here is the co(e of Hibernate 6ative SQL
package roseindia.t*torial.hibernate+ import org.hibernate.Session+ import org.hibernate.-+ import org.hibernate.criterion.-+ import org.hibernate.c!g.-+ import <ava.*til.-+ ,-.-./a*thor.Deepa%.0*mar .-. .-.http9,,))).roseindia.net.Hibernate.4ative.Q*ery.5"ample .-.. .-, public class 4ativeQ*ery5"ample.3

..public static void main(String:;.args).3 ....Session.session.7.null+ ....try3 ......,,.2his.step.)ill.read. hibernate.c!g."ml.and.prepare.hibernate.!or.*se ......Session'actory.session'actory.7. new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......session.7session'actory.openSession()+ ......,-.Hibernate.4ative.Q*ery.(verage.5"amle-, .......String.sFl.7=select. stddev(ins.invested?amo*nt).as.std5rrB.=H .........=.avg(ins.invested?amo*nt).as.mean.=H .........=.!rom.ins*rance.ins=+ .......Q*ery.F*ery.7.session.createSQLQ*ery(sFl) .addScalar(=std5rr=BHibernate.DOUBL5). .........addScalar(=mean=BHibernate.DOUBL5)+ .,,Do*ble.:;.amo*nt.7.(Do*ble.:;).F*ery.*niF*e8es*lt()+. .......Ob<ect.:;.amo*nt.7.(Ob<ect.:;) .F*ery.*niF*e8es*lt()+. .......System.o*t.println(=mean. amo*nt9.=.H.amo*nt:D;)+ .......System.o*t.println(=std5rr. amo*nt9.=.H.amo*nt:C;)+ .......,-.5"ample.to.sho).4ative. F*ery.to.select.all.the. ob<ects.!rom.database.-, .......,-.Selecting.all. the.ob<ects.!rom.ins*rance.table.-, .......List.ins*rance.7.session.createSQLQ*ery (=select..3ins.-6..!rom.ins*rance.ins=) .......add5ntity(=ins=B. ns*rance.class) .........list()+ ......for ( terator.it.7. ins*rance.iterator()+.it.has4e"t()+).3 ........ ns*rance.ins*ranceOb<ect .7.( ns*rance).it.ne"t()+ ........System.o*t.println(= D9.=. H.ins*ranceOb<ect.getLng ns*rance d())+ ........System.o*t.println(=4ame9. =.H.ins*ranceOb<ect.get ns*rance4ame())+ ......6 ...... ..........session.close()+ ....6catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ......e.printStac%2race()+ ....6 .... ..6 6

2ollo ing -uery is used to calculate the average of invested a!ount0


8PHibernate Jative Buery 7verage E1a!leP8

String s-l FAselect stddev4ins.investedKa!ount5 as stdErr, AR A avg4ins.investedKa!ount5 as !ean AR A fro! insurance insAQ "he follo ing code0 Buery -uery F session.createSB)Buery4s-l5.addScalar4AstdErrA,Hibernate.<OIB)E5. addScalar4A!eanA,Hibernate.<OIB)E5Q 6reates a ne instance of SB)Buery for the given SB) -uery string and the entities returned by the -uery are detached. "o return all the entities fro! database e have used the follo ing -uery0 8P E1a!ple to sho Jative -uery to select all the ob/ects fro! database P8 8P Selecting all the ob/ects fro! insurance table P8 )ist insurance F session.createSB)Buery4A se#ect Bins%7C from insurance insA5 .addEntity4AinsA, Insurance%c#ass5 .list45Q for 4,terator it F insurance.iterator45Q it.hasJe1t45Q5 S ,nsurance insuranceOb/ect F 4,nsurance5 it.ne1t45Q Syste!.out.println4A,<0 A R insuranceOb/ect.get)ng,nsurance,d455Q Syste!.out.println4AJa!e0 A R insuranceOb/ect.get,nsuranceJa!e455Q T ?hen you run the progra! through it should display the follo ing result0 log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select stddev4ins.investedKa!ount5 as stdErr, avg4ins.investedKa!ount5 as !ean fro! insurance ins !ean a!ount0 %'2.>%$& stdErr a!ount0 '23.%(>& Hibernate0 select ins.,< as ,<0K, ins.insuranceKna!e as insurance2K2K0K, ins.investedKa!ount as invested3K2K0K, ins.investe!entKdate as investe!&K2K0K fro! insurance ins ,<0 > Ja!e0 6ar ,nsurance ,<0 2 Ja!e0 )ife ,nsurance ,<0 3 Ja!e0 )ife ,nsurance ,<0 &

Ja!e0 6ar ,nsurance ...... ....... ,n this e1a!ple you learned ho to use Jative Buery ith Hibernate.

Associations an( :oins


"his section includes a brief introduction about 7ssociations and Joins along ith e1a!ples. Association ma$$ings0 7ssociation !appings co!es in the list of the !ost difficult thing to get right. "his section includes the canonical cases one by one. Here e starts the section fro! unidirectional !appings and co!es to the bi.directional cases. ?e@ll include the classification of associations that hether they !ap or not to an intervening /oin table and by !ultiplicity. Here e are not using the Jullable foreign 3eys since these 3eys do not re-uire good practice in traditional data !odeling. Hibernate does not re-uire the foreign 3eys since !appings or3 even if e drop the nullability constraints. Hibernate HQL Inner :oin Hibernate@s HB) language is not capable for handling the Ainner /oin onA clauses. ,f our do!ain entity !odel includes relationships defined bet een the related ob/ects then the -uery li3e this Buery -uery F session.createBuery4Afro! 6ar car inner /oin O ner o ner here o ner.Ja!e F@Minod@A5Q ill or3. HB) 3eeps the infor!ation of /oining the 6ar and O ner classes according to the association !apping contained in the hb!.1!l file. Since the association infor!ation is defined in the !apping file so there is no need to stipulate the /oin in the -uery. ,n the above -uery Afro! 6ar car here car.O ner.Ja!eF@Minod@A ill or3 too. ,nitialiLation of the collections and !any.to.one !apping re-uires the e1plicit /oins /ust to avoid laLy load errors. 7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.
OU"ml.version7=C.D=.encoding7=U2'A@=UP .OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net, hibernateAmappingA>.D.dtd=P OhibernateAmappingP

...Oclass name7=net.roseindia.Dealer=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Obag.name7=prod*ct=.inverse7= tr*e=.cascade7=allBdeleteAorphan=P ........O%ey.col*mn7=did=,P ........OoneAtoAmany.class7= net.roseindia.#rod*ct=,P ......O,bagP ...O,classP O,hibernateAmappingP

7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.


OU"ml.version7GC.DG.encoding7G*t!A@GUP OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net, hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.#rod*ct=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Oproperty.name7=did=.type7=int=,P ......Oproperty.name7=price=.type7=do*ble=,P ......OmanyAtoAone.name7=dealer=.class7= net.roseindia.Dealer=.col*mn7=did=. insert7=!alse=.*pdate7=!alse=,P ...O,classP . O,hibernateAmappingP

Here is the hibernate co(e ,n this e1a!ple first e create the session ob/ect ith the help of the Session2actory interface. "hen e use the createBuery45 !ethod of the Session ob/ect hich returns a Buery ob/ect. Jo e use the openSession45 !ethod of the Session2actory interface si!ply to instantiate the Session ob/ect. 7nd the e retrieve the data fro! the database store it in that Buery ob/ect and iterate this ob/ect ith the help of ,terator and finally displays the re-uested data on the console.
package net.roseindia+ import <ava.*til. terator+ import <ava.*til.List+

import import import import

org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+

public class 1oin.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.sFl?F*ery.7.=!rom. #rod*ct.p.inner.<oin.p.dealer.as.d=+ ......Q*ery.F*ery.7.sess.createQ*ery(sFl?F*ery)+ ...... terator.ite.7.F*ery.list().iterator()+ ......System.o*t.println(=Dealer. 4ameVt=H=#rod*ct.4ameVt=H=#rice=)+ ......while (.ite.has4e"t().).3 ..........Ob<ect:;.pair.7.(Ob<ect:;).ite.ne"t()+ ..........#rod*ct.pro.7.(#rod*ct).pair:D;+ ..........Dealer.dea.7.(Dealer).pair:C;+ ..........System.o*t.print(pro.get4ame())+ ..........System.o*t.print(=Vt=Hdea.get4ame())+ ..........System.o*t.print(=VtVt=Hpro.get#rice())+ ..........System.o*t.println()+ ......6 ......sess.close()+ ....6 ....catch(5"ception.e.)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

!ut$ut
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select product0K.id as id>K0K, dealer>K.id as id0K>K, product0K.na!e as na!e>K0K, product0K.did as did>K0K, product0K.price as price>K0K, dealer>K.na!e as na!e0K>K fro! +roduct product0K inner /oin <ealer dealer>K on product0K.didFdealer>K.id <ealer Ja!e +roduct Ja!e +rice

6o!puter =eyboard 6o!puter :obile +en<rive )aptop Hard<is3

7gra al 7gra al 7gra al :ohan :ohan 9itu 9itu

23000.0 >%00.0 >00.0 >%000.0 200.0 200.0 2%00.0

Hibernate Aggregate Functions&Associations an( :oins'


"his e1a!ple tries to !a3e understand about the aggregate function of Hibernate ith the help of e1a!ple. ,n Hibernate HB) -ueries are capable of returning the results of the aggregate functions on properties. 6ollections can also be used ith the aggregate functions ith the select clause. 7ggregate functions supports the follo ing functions0

!in4...5, !a14...5, su!4...5, avg4...5. count4P5 count4distinct...5, count4all..5, count4...5

"he distinct and all 3ey ords used above are identical as in SB). 7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.
OU"ml.version7=C.D=.encoding7=U2'A@=UP .OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net ,hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.Dealer=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Obag.name7=prod*ct=.inverse7=tr*e= .cascade7=allBdeleteAorphan=P ........O%ey.col*mn7=did=,P ........OoneAtoAmany.class7=net.roseindia.#rod*ct=,P

......O,bagP ...O,classP O,hibernateAmappingP

7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.


OU"ml.version7GC.DG.encoding7G*t!A@GUP OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net, hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.#rod*ct=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Oproperty.name7=did=.type7=int=,P ......Oproperty.name7=price=.type7=do*ble=,P ......OmanyAtoAone.name7=dealer=.class7= net.roseindia.Dealer=.col*mn7=did=. insert7=!alse=.*pdate7=!alse=,P ...O,classP . O,hibernateAmappingP

,n this e1a!ple first e create the session ob/ect ith the help of the Session2actory interface. "hen e use the createBuery45 !ethod of the Session ob/ect hich returns a Buery ob/ect. Jo e use the openSession45 !ethod of the Session2actory interface si!ply to instantiate the Session ob/ect. 7nd the e retrieve the data fro! the database store it in that Buery ob/ect and iterate this ob/ect ith the help of ,terator and finally displays the re-uested data on the console. Here is the hibernate co(e
package net.roseindia+ import <ava.*til. terator+ import <ava.*til.List+ import import import import org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+

public class (ggregate'*nction5"ample.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3

....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.sFl?F*ery.7.=select. d.nameBp.nameBs*m(p.price).as .totalprice.!rom.#rod*ct. p.<oin.p.dealer.d.gro*p.by.p.name=+ ......Q*ery.F*ery.7.sess.createQ*ery(sFl?F*ery)+ ......System.o*t.println(=Dealer. 4ameVt=H=#rod*ct.4ameVt=H=#rice=)+ ......for( terator.it7 F*ery.iterate()+it.has4e"t()+)3 ........Ob<ect:;.ro).7.(Ob<ect:;).it.ne"t()+ ........System.o*t.print(ro):D;)+ ........System.o*t.print(=VtVt=Hro):C;)+ ........System.o*t.print(=Vt=Hro):2;)+ ........System.o*t.println()+ ......6 ....sess.close()+ ....6 ....catch(5"ception.e.)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

!ut$ut

log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select dealer>K.na!e as colK0K0K, product0K.na!e as colK>K0K, su!4product0K.price5 as colK2K0K fro! +roduct product0K inner /oin <ealer dealer>K on product0K.didFdealer>K.id group by product0K.na!e <ealer Ja!e 7gra al 9itu 7gra al 9itu :ohan :ohan +roduct Ja!e 6o!puter Hard<is3 =eyboard )aptop :obile +en<rive +rice 23>00.0 2%00.0 >%00.0 200.0 >%000.0 200.0

Hibernate Sub)ueries
,n this section, you ill learn about the sub-ueries ith an appropriate e1a!ple. Sub-ueries in hibernate can be referred as the -ueries that are surrounded by parentheses 45. Sub-ueries solves the purpose of grouping, ordering , narro ing and aggregating the resultant of the -uery by using the here clause. Jotice that the sub-ueries get e1ecuted prior to the !ain -uery. "he HB) -ueries !ay contain the sub-ueries only in case of if the sub-ueries are supported by the underline database. 7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.
OU"ml.version7=C.D=.encoding7=U2'A@=UP .OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net,hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.Dealer=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Obag.name7=prod*ct=.inverse7=tr*e=.cascade7=allBdeleteAorphan=P ........O%ey.col*mn7=did=,P ........OoneAtoAmany.class7=net.roseindia.#rod*ct=,P

......O,bagP ...O,classP O,hibernateAmappingP

7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.


OU"ml.version7GC.DG.encoding7G*t!A@GUP OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net,hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.#rod*ct=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Oproperty.name7=did=.type7=int=,P ......Oproperty.name7=price=.type7=do*ble=,P ......OmanyAtoAone.name7=dealer=.class7=net.roseindia.Dealer=.col*mn7=did=. insert7=!alse=.*pdate7=!alse=,P ...O,classP . O,hibernateAmappingP

Here is the hibernate co(e ,n this e1a!ple first e create the session ob/ect ith the help of the Session2actory interface. "hen e use the createBuery45 !ethod of the Session ob/ect hich returns a Buery ob/ect. Jo e use the openSession45 !ethod of the Session2actory interface si!ply to instantiate the Session ob/ect. 7nd the e retrieve the data fro! the database store it in that Buery ob/ect and iterate this ob/ect ith the help of ,terator and finally displays the re-uested data on the console.
package net.roseindia+ import <ava.*til. terator+ import <ava.*til.List+ import import import import org.hibernate.Q*ery+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+

public class S*bF*eries.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+

....try3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......String.sFl?F*ery.7.=select.d.nameBp.nameBp.price.!rom.#rod*ct.p.<oin.p.dealer. d.)here.p.price.in(select.p.price.!rom.p.)here.p.price.P.CJDD)=+ ......Q*ery.F*ery.7.sess.createQ*ery(sFl?F*ery)+ ......System.o*t.println(=Dealer.4ameVt=H=#rod*ct.4ameVt=H=#rice=)+ ......for( terator.it7F*ery.iterate()+it.has4e"t()+)3 ........Ob<ect:;.ro).7.(Ob<ect:;).it.ne"t()+ ........System.o*t.print(ro):D;)+ ........System.o*t.print(=VtVt=Hro):C;)+ ........System.o*t.print(=Vt=Hro):2;)+ ........System.o*t.println()+ ......6 ....sess.close()+ ....6 ....catch(5"ception.e.)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

!ut$ut
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select dealer>K.na!e as colK0K0K, product0K.na!e as colK>K0K, product0K.price as colK2K0K fro! +roduct product0K inner /oin <ealer dealer>K on product0K.didFdealer>K.id here product0K.price in 4select product0K.price fro! +roduct product0K here product0K.priceG>%005 <ealer Ja!e 7gra al :ohan 9itu +roduct Ja!e +rice 6o!puter :obile Hard<is3 23000.0 >%000.0 2%00.0

Hibernate Pro"ections
,n this section, you ill learn about the hibernate pro/ections ith an appropriate e1a!ple. Pro"ections0 "he pac3age Criteria is used as a fra!e or3 by the applications /ust to build the ne 3inds of pro/ection. !ay be used by applications as a fra!e or3 for building ne 3inds of Pro"ection% ,n general +ro/ection !eans to retrieve hile in case of SB) +ro/ection !eans ASe#ectA clause. :ost of the applications uses the built.in pro/ection types by !eans of the static factory !ethods of this class. Pro(uct%"ava

package net.roseindia+ public class #rod*ct.3 .. ..private int id+ ..private String.name+ ..private double price+ ..private Dealer.dealer+ ..private int did+ .. ..public #rod*ct(String.nameB.double price).3 ....super()+ ....,,.2ODO.(*toAgenerated.constr*ctor.st*b ....this.name.7.name+ ....this.price.7.price+ ..6 ..public #rod*ct().3 ....super()+ ....,,.2ODO.(*toAgenerated.constr*ctor.st*b ..6 ..public Dealer.getDealer().3 ....return dealer+ ..6 ..public void setDealer(Dealer.dealer).3 ....this.dealer.7.dealer+ ..6 .. ..public double getDid().3 ....return did+ ..6 ..public void setDid(int did).3 ....this.did.7.did+ ..6 .. ..public int get d().3 ....return id+ ..6 ..public void set d(int id).3 ....this.id.7.id+ ..6 ..public String.get4ame().3 ....return name+ ..6 ..public void set4ame(String.name).3 ....this.name.7.name+ ..6 ..public double get#rice().3 ....return price+ ..6 ..public void set#rice(double price).3 ....this.price.7.price+ ..6 6

Pro"ectionList is the list of pro/ection instances hich are result of Buery@s ob/ect. Criteria API enables us to specify criteria based on various. ,n the class $ro"ection2,am$#e%"ava@ first e create the session ob/ect ith the help of the Session2actory interface. "hen e use the createQuery&' !ethod of the Session ob/ect hich returns a Buery ob/ect. Jo e use the openSession45 !ethod of the Session2actory interface si!ply to instantiate the Session ob/ect. "hen e obtain the criteria ob/ect si!ply by invo3ing the create6riteria45 !ethod of the Session@s ob/ect. Jo e create a pro/ection)ist ob/ect add the fields having properties -name- and -$rice-% Set it to the 6riteria ob/ect by invo3ing the setPro"ection&' !ethod and passing the pro/ect)ist ob/ect into this !ethod and then add this ob/ect into the )ist interface@s list ob/ect and iterate this ob/ect list ob/ect to display the data contained in this ob/ect. $ro"ection2,am$#e%"ava
package net.roseindia+ import <ava.*til. terator+ import <ava.*til.List+ import import import import import import org.hibernate.Criteria+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+ org.hibernate.criterion.#ro<ectionList+ org.hibernate.criterion.#ro<ections+

public class pro<ection5"ample.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b .... ....Session.sess.7.null+ ....try3 ......Session'actory.s!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.s!act.openSession()+ ......Criteria.crit.7.sess.createCriteria(#rod*ct.class)+ ......#ro<ectionList.proList.7.#ro<ections.pro<ectionList()+ ......proList.add(#ro<ections.property(=name=))+ ......proList.add(#ro<ections.property(=price=))+ ......crit.set#ro<ection(proList)+ ......List.list.7.crit.list()+ ...... terator.it.7.list.iterator()+ ......if(Eit.has4e"t())3 ........System.o*t.println(=4o.any.dataE=)+ ......6 ......else3 ........while(it.has4e"t())3 ..........Ob<ect:;.ro).7.(Ob<ect:;)it.ne"t()+ ..........for(int i.7.D+.i.O.ro).length+iHH)3 ............System.o*t.print(ro):i;)+

............System.o*t.println()+ ..........6 ........6 ......6 ......sess.close()+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

!ut$ut
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select thisK.na!e as y0K, thisK.price as y>K fro! +roduct thisK +roduct Ja!e 6o!puter :obile )aptop =eyboard +en<rive Hard<is3 6o!puter +rice 23000.0 >%000.0 200.0 >%00.0 200.0 2%00.0 >00.0

Hibernate Pro"ections &ro=Count or count+istinct'


,n this section, you ill learn about the hibernate pro/ection ith an e1a!ple. Pro"ection Interface "his is an interface that e1tends the Seria#iDab#e. 7n ob/ect.oriented representation of a -uery result set pro/ection in a Criteria -uery. Built.in pro/ection types are provided by the Projections factory class. "he +ro/ection interface !ight be i!ple!ented by application classes that define custo! pro/ections. "he follo ing e1a!ple to count the total nu!ber of ro s and distinct ro s to use the Pro"ections%ro=Count&' and Pro"ections%count+istinct&' !ethod.

Tab#e 6ame Insurance

Here is the co(e of $rogram


package roseindia.t*torial.hibernate+ import <ava.*til. terator+ import <ava.*til.List+ import import import import import org.hibernate.Criteria+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+ org.hibernate.criterion.#ro<ections+

public class hibernate#ro<ection5"ample.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b ....Session.sess.7.null+ ....try3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......Criteria.crit.7.sess.createCriteria( ns*rance.class)+ ......crit.set#ro<ection(#ro<ections.ro)Co*nt())+ ......List.res*lt.7.crit.list()+ ......System.o*t.println(=4o..o!.ro)s9.=Hres*lt)+ ......crit.set#ro<ection(#ro<ections.distinct(#ro<ections.co*ntDistinct(=ins*rance4 ame=)))+ ......List.distList.7.crit.list()+ ......System.o*t.println(=Distinct.Co*nt9..=H.distList)+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

+o=n#oa( this Co(e%

!ut$ut
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select count4P5 as y0K fro! insurance thisK Jo. of ro s0 U(V Hibernate0 select distinct count4distinct thisK.insuranceKna!e5 as y0K fro! insurance thisK <istinct 6ount0 U%V

Hibernate Pro"ection Count


,n this section, you ill learn to hibernate pro/ection count. "he e1a!ple de!onstrates the ro=Count&' !ethod of the pro/ection interface. 7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.
OU"ml.version7=C.D=.encoding7=U2'A@=UP .OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net,hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.Dealer=P ......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Obag.name7=prod*ct=.inverse7=tr*e=.cascade7=allBdeleteAorphan=P ........O%ey.col*mn7=did=,P ........OoneAtoAmany.class7=net.roseindia.#rod*ct=,P ......O,bagP ...O,classP O,hibernateAmappingP

7 unidirectional one.to.!any association on a foreign 3ey is rarely re-uired.


OU"ml.version7GC.DG.encoding7G*t!A@GUP OEDOC2K#5.hibernateAmapping ...#UBL C.=A,,Hibernate,Hibernate.$apping.D2D,,54= ...=http9,,hibernate.so*rce!orge.net,hibernateAmappingA>.D.dtd=P OhibernateAmappingP ...Oclass name7=net.roseindia.#rod*ct=P

......Oid.name7=id=.type7=int=P .........Ogenerator.class7=increment=,P ......O,idP ......Oproperty.name7=name=.type7=string=,P ......Oproperty.name7=did=.type7=int=,P ......Oproperty.name7=price=.type7=do*ble=,P ......OmanyAtoAone.name7=dealer=.class7=net.roseindia.Dealer=.col*mn7=did=. insert7=!alse=.*pdate7=!alse=,P ...O,classP . O,hibernateAmappingP

Here is the hibernate co(e ,n the class $ro"ection2,am$#e%"ava@ first e create the session ob/ect ith the help of the Session2actory interface. "hen e use the createBuery45 !ethod of the Session ob/ect hich returns a Buery ob/ect. Jo e use the openSession45 !ethod of the Session2actory interface si!ply to instantiate the Session ob/ect. "hen e obtain the criteria ob/ect si!ply by invo3ing the create6riteria45 !ethod of the Session@s ob/ect. Jo e set the nu!ber of ro s count si!ply by calling the set+ro/ection45 !ethod of the 6riteria 7+,s and passing it the ro 6ount45 !ethod of the +ro/ections interface. "hen pass the reference of the 6riteria ob/ect into the )ist interface ob/ect and finally iterate this ob/ect to count the nu!ber of ro s.
package net.roseindia+ import <ava.*til. terator+ import <ava.*til.List+ import import import import import import import org.hibernate.Criteria+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+ org.hibernate.criterion.#ro<ection+ org.hibernate.criterion.#ro<ections+ org.hibernate.criterion.8estrictions+

public class pro<ectionCo*nt.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b .... ....Session.sess.7.null+ ....try 3 ......Session'actory.s!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.s!act.openSession()+ ......Criteria.crit.7.sess.createCriteria(#rod*ct.class)+ ..........crit.set#ro<ection(#ro<ections.ro)Co*nt())+ ..........List.list.7.crit.list()+

...... terator.it.7.list.iterator()+ ......if (Eit.has4e"t())3 ........System.o*t.println(=4o.any.dataE=)+ ......6 ......else3 ........while(it.has4e"t())3 ..........Ob<ect.co*nt.7.it.ne"t()+ ..........System.o*t.println(=8o)9.=.H.co*nt)+.. ........6 ......6 ...... ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

!ut$ut
log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select count4P5 as y0K fro! +roduct thisK 9o 0 (

Hibernate Pro"ection 2,am$#e &Sum'


,n this section, you ill learn to hibernate aggregate function li3e0 sum&' using hibernate pro/ection. "he follo ing e1a!ple to calculate the su! of investedKa!ount to the ,nsurance table Tab#e 6ame Insurance

Here is the co(e of $rogram

package roseindia.t*torial.hibernate+ import <ava.*til.List+ import import import import import import org.hibernate.Criteria+ org.hibernate.Session+ org.hibernate.Session'actory+ org.hibernate.c!g.Con!ig*ration+ org.hibernate.criterion.#ro<ectionList+ org.hibernate.criterion.#ro<ections+

public class #ro<ection5"ampleC.3 ..,-...-./param.args ...-, ..public static void main(String:;.args).3 ....,,.2ODO.(*toAgenerated.method.st*b .... ....Session.sess.7.null+ ....try 3 ......Session'actory.!act.7.new Con!ig*ration().con!ig*re().b*ildSession'actory()+ ......sess.7.!act.openSession()+ ......Criteria.crit.7.sess.createCriteria( ns*rance.class)+ ......#ro<ectionList.proList.7.#ro<ections.pro<ectionList()+ ......proList.add(#ro<ections.s*m(=investement(mo*nt=))+ ......crit.set#ro<ection(proList)+ ......List.s*m8es*lt.7.crit.list()+ ......System.o*t.println(=2otal. nvested.(mo*nt9.=.H.s*m8es*lt)+ ....6 ....catch(5"ception.e)3 ......System.o*t.println(e.get$essage())+ ....6 ..6 6

+o=n#oa( this Co(e% !ut$ut


log&/0?79J Jo appenders could be found for logger 4org.hibernate.cfg.Environ!ent5. log&/0?79J +lease initialiLe the log&/ syste! properly. Hibernate0 select su!4thisK.investedKa!ount5 as y0K fro! insurance thisK "otal ,nvested 7!ount0 U%>&00V

Hibernate Ty$es

"his section gives you description of all the "ypes that are supported by Hibernate. 7 Hibernate "ype is used to !ap a Java property type to a J<B6 type or types. "he follo ing tables to represents all Hibernate types0 Interfaces an( +escri$tions "he 7bstract6o!ponent"ype enables other 6o!ponent.li3e types to AbstractCom$onentTy$e hold collections and have cascades, etc. AssociationTy$e "his interface used to represent all associations bet een entities. "his interface used to discri!inator properties ith the help of right +iscriminatorTy$e !apped subclass. I(entifierTy$e "his interface has 7ll identifiers of entities. Litera#Ty$e "his is a !a3er interface that hich store SB) literals. "his interface describes !apping bet een the Java and J<B6 Ty$e datatypes EersionTy$e "his interface used for version sta!ping.

C#asses an( +escri$tions Abstract;ynaryTy$e AbstractCharArrayTy$e AbstractTy$e

"he strea! of byte bounded into a M7B9B,J79C. "he strea! of char bounded into a M796H79. "his is a superclass that can be used for creating type hierarchy.

A(a$te(Immutab#eTy$e AnyTy$e ,t defines @any@ !appings and deprecated @ob/ect@ types. AnyTy$e%!b"ectTy$eCache2ntry ArrayTy$e ,t represents collection of data into a si!ilar types. ;agTy$e "his class used to !apping bet een SB) JI:E9,6 and ;ig+ecimaTy$e /ava.!ath.Big<eci!al. "his class used to !apping bet een SB) JI:E9,6 and ;igIntegerTy$e /ava.!ath.Big,nteger. ,t used to !apping bet een a SB) M79B,J79C and a ;inaryTy$e Java byteUV. ,t used to !apping bet een a SB) B)OB and ;#obTy$e /ava.s-l.Blob. ;oo#eanTy$e "his class !aps bet een SB) B," and Java Boolean. ;yteTy$e "his class !aps bet een SB) ",JC,J" and Java Byte. "his class represents a data and !apping into a 6alendar Ca#en(ar+ateTy$e ob/ect.

Ca#en(arTy$e CharacterArrayTy$e CharacterTy$e CharArrayTy$e Char;oo#eanTy$e C#assTy$e C#obTy$e Co##ectionTy$e Com$onentTy$e Com$ositeCustomTy$e CurrencyTy$e CustomCo##ectionTy$e CustomTy$e +ateTy$e +bTimestam$Ty$e +oub#eTy$e 2mbe((e(Com$onentTy$e 2ntityTy$e F#oatTy$e ForeignFey+irection I(entifier;agTy$e Immutab#eTy$e IntegerTy$e ListTy$e Loca#eTy$e LongTy$e ManyTo!neTy$e Ma$Ty$e MetaTy$e Mutab#eTy$e 6u##ab#eTy$e

,t also represents a dateti!e !apping into a 6alendar ob/ect. ,t is a collection of M796H79 li3e0 6haracterUV. "his class !apping bet een a SB) 6H79 and a Java 6haracter. ,t is a collection of M796H79 li3e0 charUV. "his is a superclass that can be !apping bet een SB) 6H79 and Java boolean. "his class !apping bet een SB) M796H79 and Java class. "his class !apping bet een SB) 6)OB and /ava.s-l.6lob. ,t handles the Hibernate +ersistent6ollections. "his class !apping all co!ponents. ,t ad/usts 6o!positeIser"ype to "ype interface.Q ,t is used to !apping a SB) M796H79 into a /ava.util.6urrency. "his class is created by users and i!ple!ent the +ersistent6ollection. ,t ad/usts the user type to generic type interface and changes the internal type contracts. "his class !apping bet een an SB) <7"E to Java <ate. ,t can be used to !apping bet een SB) <OIB)E to Java <ouble. ,t co!!unicates an entity class. ,t lin3s SB) 2)O7" to Java 2loat. "his class sho s directionality of the foreign 3ey constraint. "his is a superclass of the nullable i!!utable type. "his class lin3s bet een the SB) ,J" to Java ,nteger. ,t lin3s into an SB) M796H79 and a Java )ocale. "his class lin3s into an SB) B,*,J" and a Java )ong. ,t associates !any.to.one entity.

"his is a superclass of !utable nullable types. "his is a supperclass of single.colu!n nullable types.

!neTo!neTy$e !r(ere(Ma$Ty$e !r(ere(SetTy$e PrimitiveTy$e Seria#iDab#eTy$e SetTy$e ShortTy$e Sorte(Ma$Ty$e Sorte(SetTy$e S$acia#!neTo!neTy$e StringTy$e Te,tTy$e Timestam$Ty$e TimeTy$e TimeGoneTy$e TrueFa#seTy$e Ty$eFactory Wra$$er;inaryTy$e >es6oTy$e

,t associates one.to.one entity.

"his is the superclass of pri!itive or pri!itive rappers types. "his class !aps an SB) M79B,J79C to a serialiLable Java ob/ect. ,t co!!unicates bet een an SB) S:7)),J" and Java Short.

,t co!!unicates bet een an SB) M796H79 and Java String. "his class lin3s bet een an SB) 6)OB and Java String. "his class !apping bet een an SB) ",:ES"7:+ and Java /ava.util.<ate or /ava.s-l."i!esta!p. ,t !aps an SB) ",:E to Java /ava.util.<ate or /ava.s-l."i!e. ,t co!!unicates an SB) M796H79 to Java /ava.util."i!eWone. "his class !aps an SB) 6H79 to a Java Boolean. "his class used internally and holds an instance of "ype. ,t !aps bet een an SB) 6H79 to Java Boolean.

2,ce$tions an( +escri$tions "his e1ception occurs hen the property could not be serialiLed Seria#iDation2,ce$tion or deserialiLed.

You might also like