Hibernate Interview Questions – Part 4

Hibernate Interview Questions (Part 1 – Part 2Part 3)

HQL – Hibernate Query Language:

Why HQL?
Most of the applications use Databases like Oracle, SQL etc. So when writing an application we use specific queries to access database. SQL Query might be different when compared with Oracle Query to access databases. So if database with which the application works changes, We need to change the queries accordingly to access the database. To overcome this we use HQL.


Query:
In hibernate we use,
Query query = session.createQuery();



Commonly used class in HQL:
From:
Query query = session.createQuery(FROM entityname);

SELECT:
Query query = session.createQuery(SELECT empid from Employee);

WHERE:
Query query = session.createQuery(FROM employee WHERE empname = ’employeename’);


How to Bind Parameters in Query?
We can bind parameters in HQL,
Query query = session.createQuery(“FROM employee WHERE ename= :ename”);
Now we have to pass value to that parameter,
String ename = “Alpha”;
query.setString(“ename”,ename); (for integers its query.setInteger)


How to use Iterator?
Query query = session.createQuery(“FROM employee”);
for(Iterator itr = query.iterate(); itr.hasNext(); ;){
Employee emp = (Employee) itr.next();
}


How can we use Native SQL Query in Hibernate?
SQLQuery Session.createSQLQuery(String queryString);


Criteria Queries:
Criteria Queries are used to check multiple conditions and add restrictions in a query.
To create Criteria Queries,
Criteria createCriteria


Adding Restrictions in a Query
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq(“columnname”, “condition”));


Criteria Queries with Restrictions:

.add(Restrictions.eq(Propertyname, object value) – This will compare the property name equals to the object value

.add(Restrictions.gt(Propertyname, object value) – This will return the results when the value of that property is greater than the specified value

.add(Restrictions.lt(Propertyname, object value) – This will return the results when the value of that property is lesser than the specified value

.add(Restrictions.ge(Propertyname, object value) – This will return the results when the value of that property is greater than or equal to the specified value

.add(Restrictions.le(Propertyname, object value) – This will return the results when the value of that property is lesser than or equal to the specified value

.add(Restrictions.like(Propertyname, object value) – This will compare the propertywith specified pattern

.add(Restrictions.between(Propertyname, object low, object high) – This method compares the property within the range of low and high

Example here


 

 

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *