HQL (Hibernate Query Language) Tutorial

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

HQL(HibernateQueryLanguage)TutorialwithExamples

1.
HibernateQueryLanguage(HQL)issameasSQL(StructuredQueryLanguage)butitdoesn'tdepends
onthetableofthedatabase.Insteadoftablename,weuseclassnameinHQL.Soitisdatabase
independentquerylanguage.

AdvantageofHQL
TherearemanyadvantagesofHQL.Theyareasfollows:
databaseindependent
supportspolymorphicqueries
easytolearnforJavaProgrammer

QueryInterface
ItisanobjectorientedrepresentationofHibernateQuery.TheobjectofQuerycanbeobtainedby
callingthecreateQuery()methodSessioninterface.
Thequeryinterfaceprovidesmanymethods.Thereisgivencommonlyusedmethods:
1.publicintexecuteUpdate()isusedtoexecutetheupdateordeletequery.
2.publicListlist()returnstheresultoftheralationasalist.
3.publicQuerysetFirstResult(introwno)specifiestherownumberfromwhererecordwillbe
retrieved.
4.publicQuerysetMaxResult(introwno)specifiestheno.ofrecordstoberetrievedfromtherelation
(table).
5.publicQuerysetParameter(intposition,Objectvalue)itsetsthevaluetotheJDBCstylequery
parameter.
6.publicQuerysetParameter(Stringname,Objectvalue)itsetsthevaluetoanamedquery
parameter.

ExampleofHQLtogetalltherecords
1.Queryquery=session.createQuery("fromEmp")//herepersistentclassnameisEmp
2.Listlist=query.list()

ExampleofHQLtogetrecordswithpagination

1.Queryquery=session.createQuery("fromEmp")
2.query.setFirstResult(5)
3.query.setMaxResult(10)
4.Listlist=query.list()//willreturntherecordsfrom5to10thnumber

ExampleofHQLupdatequery
1.Transactiontx=session.beginTransaction()
2.Queryq=session.createQuery("updateUsersetname=:nwhereid=:i")
3.q.setParameter("n","UditKumar")
4.q.setParameter("i",111)
5.intstatus=q.executeUpdate()
6.System.out.println(status)
7.tx.commit()

ExampleofHQLdeletequery
1.Queryquery=session.createQuery("deletefromEmpwhereid=100")
2.//specifyingclassname(Emp)nottablename
3.query.executeUpdate()

HQLwithAggregatefunctions
Youmaycallavg(),min(),max()etc.aggregatefunctionsbyHQL.Let'sseesomecommonexamples:

Exampletogettotalsalaryofalltheemployees
1.Queryq=session.createQuery("selectsum(salary)fromEmp")
2.List<Emp>list=q.list()
3.Iterator<Emp>itr=list.iterator()
4.while(itr.hasNext()){
5.System.out.println(itr.next())
6.}

Exampletogetmaximumsalaryofemployee
1.Queryq=session.createQuery("selectmax(salary)fromEmp")

Exampletogetminimumsalaryofemployee
1.Queryq=session.createQuery("selectmin(salary)fromEmp")

ExampletocounttotalnumberofemployeeID

1.Queryq=session.createQuery("selectcount(id)fromEmp")

Exampletogetaveragesalaryofeachemployees
1.Queryq=session.createQuery("selectavg(salary)fromEmp")
NextTopicHCQL

You might also like