Hibernate uses a query language- HQL which is similar to SQL. Compared to SQL, HQL is object oriented and works with persistent object. We can use native SQL query also with hibernate, but we should use HQL so that their will not be any issue related to portability.
Example:
String hqs = "FROM Employee"; //Simple Query String hqs = "FROM Employee as emp"; //Using As a clause String hqs = "FROM Employee emp"; //As clause is not mandatory String hqs = "FROM Employee , Country"; //Multiple tables
Example:
String hqs = "SELECT E.name FROM Employee E"; // selecting name property only
Example:
String hqs = "SELECT SUM(emp.salary), emp.name FROM Employee emp " + "GROUP BY E.name";
The supported aggregate functions are:
avg(...), sum(...), min(...), max(...)
count(*)
count(...), count(distinct ...), count(all...)
Example:
String hqs = "FROM Employee WHERE name = "Ankit"";
Example:
String hqs = "FROM Employee WHERE id > 10 ORDER BY name DESC";
Example:
String hqs = "SELECT SUM(emp.salary), emp.name FROM Employee emp " + "GROUP BY E.name";
Example:
String hqs = "FROM Employee WHERE id = :emp_id"; Query query = session.createQuery(hqs); query.setParameter("emp_id",10); List results = query.list();
Example:
String hqs = "UPDATE Employee set name = :emp_name " + "WHERE id = :emp_id";
Example:
String hqs = "DELETE FROM Employee " + "WHERE id = :emp_id";
Example:
String hqs = "INSERT INTO HeadEmployee(name, salary)" + "SELECT name, salary FROM Employee";
Example:
String hqs = "FROM Employee as emp where emp.id in ( select empid from HeadEmployee hemp )
We can bound the result set for maximum number of rows to be fetched or the first row we wan to retrieve.
Example:
Query q = sess.createQuery("from Employee emp"); q.setFirstResult(5); // 5th row from DB will be first row in your resultset. q.setMaxResults(10); //to retrieve a fixed number maxResults of objects.