Hibernate Query Language
~1 min read
·
Hibernate
Hibernate Query Language (HQL ) is an object-oriented query language similar to SQL, but designed for Hibernate. It operates on entity objects instead of database tables.
Select All Records: Equivalent to: SELECT * FROM student; Uses entity name ( Student ) instead of table name.
import java.util.List;
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
String hql = "FROM Student" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
// Loop using for-each
for (Student student : students) {
System.out.println("Name: " + student.getName());
System.out.println("----------------------" );
}
transaction.commit();
session.close();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Select Specific Columns: Returns specific fields instead of full entity objects.
import java.util.List;
String hql = "SELECT s.name, s.email FROM Student s" ;
List <Object []> results = session.createQuery(hql,Object [].class ).getResultList();
for (Object [] row : results) {
System.out.println("Name: " + row[0 ] + ", email: " + row[1 ]);
}
transaction.commit();
session.close();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
HQL with WHERE Clause: Uses :parameter to prevent SQL injection . Equivalent SQL : SELECT * FROM student WHERE name = 'Alice';
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
String hql = "FROM Student WHERE name = :studentName" ;
Student student = session.createQuery(hql, Student.class )
.setParameter("studentName" , "David" )
.uniqueResult();
System.out.println(student.getEmail());
transaction.commit();
session.close();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Ordering Results: ORDER BY Sorts results alphabetically by name .
String hql = "FROM Student ORDER BY name ASC" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
ORDER BY DESC Sorts by age in descending order .
String hql = "FROM Student ORDER BY age DESC" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Filtering with LIKE (Pattern Matching): Fetches all students whose names start with 'A' .
String hql = "FROM Student WHERE name LIKE 'A%'" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
HQL Joins: Inner Join Fetches students enrolled in Java course .
String hql = "SELECT s FROM Student s INNER JOIN s.courses c WHERE c.title = 'Java'" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Left Join Includes students even if they don’t have courses.
String hql = "SELECT s FROM Student s LEFT JOIN s.courses c" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Fetch Join (Eager Loading) Prevents LazyInitializationException by eagerly fetching related entities .
String hql = "FROM Student s JOIN FETCH s.courses" ;
List <Student > students = session.createQuery(hql, Student.class ).getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Aggregation Functions (COUNT, SUM, AVG, MIN, MAX): Count Total Students
String hql = "SELECT COUNT(s) FROM Student s" ;
Long count = session.createQuery(hql, Long.class ).getSingleResult();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Find Sum Age
String hql = "SELECT SUM(s) FROM Student s" ;
Integer count = session.createQuery(hql, Integer.class ).getSingleResult();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Find Average Age
String hql = "SELECT AVG(s.age) FROM Student s" ;
Double avgAge = session.createQuery(hql, Double.class ).getSingleResult();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Find Minimum Age
String hql = "SELECT MIN(s.age) FROM Student s" ;
Integer minAge = session.createQuery(hql, Integer.class ).getSingleResult();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Find Maximum Age
String hql = "SELECT MAX(s.age) FROM Student s" ;
Integer minAge = session.createQuery(hql, Integer .class ).getSingleResult();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Updating Data in HQL: Equivalent SQL : UPDATE student SET age = 25 WHERE name = 'Alice';
String hql = "UPDATE Student SET age = :newAge WHERE name = :studentName" ;
int updatedCount = session.createQuery(hql)
.setParameter("newAge" , 25 )
.setParameter("studentName" , "Alice" )
.executeUpdate();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Deleting Data in HQL: Equivalent SQL : DELETE FROM student WHERE name = 'Bob';
String hql = "DELETE FROM Student WHERE name = :studentName" ;
int deletedCount = session.createQuery(hql)
.setParameter("studentName" , "Bob" )
.executeUpdate();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Pagination in HQL: Hibernate allows pagination using setFirstResult() and setMaxResults() .
String hql = "FROM Student" ;
List <Student > students = session.createQuery(hql, Student.class )
.setFirstResult(5 ) // Skips first 5 records (Page 2)
.setMaxResults(5 ) // Fetch next 5 records
.getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Named Queries (@NamedQuery): A Named Query allows you to define HQL queries inside entity classes . Benefits : Code is cleaner & easier to maintain.
Defining Named Query:
@Entity
@NamedQuery(name = "Student.findByName" , query = "FROM Student WHERE name = :name" )
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id ;
private String name ;
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Using Named Query:
List <Student > students = session.createNamedQuery("Student.findByName" , Student.class )
.setParameter("name" , "Alice" )
.getResultList();
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">