🔹 HQL (Hibernate Query Language)
✅ Object-oriented query language → queries are written against Java entities and their properties, not database tables or columns.
✅ Portable → Hibernate translates HQL into database-specific SQL, so you can switch databases without changing your queries.
✅ Database-agnostic → doesn’t rely on vendor-specific SQL features.
✅ Supports polymorphism → you can query superclasses and retrieve subclass instances.
✅ Uses Java class names and field names (e.g., FROM User WHERE username = :username
).
🔹 SQL (Structured Query Language)
✅ Traditional, vendor-specific language used directly with relational databases.
✅ Written against physical tables and columns, not entities → tightly coupled to the database schema.
✅ Portable only if you avoid vendor-specific SQL features (which is rare in practice).
✅ Doesn’t understand object-oriented concepts like inheritance or relationships in your Java model.
✅ Example: SELECT * FROM users WHERE username = ?
.
🔹 Key differences summarized:
Feature | HQL | SQL |
---|---|---|
Operates on | Entities & fields (OOP) | Tables & columns (DB) |
Portability | Database-independent | Vendor-dependent |
Translation | Converted to SQL by Hibernate | Sent directly to DB |
Object concepts | Supports polymorphism, relationships | No awareness of OOP |
Use case | Works with Hibernate entities | Direct DB operations, reports |
🔹 Example: same query in both:
✅ HQL
String hql = "FROM User u WHERE u.username = :username";
session.createQuery(hql, User.class)
.setParameter("username", "john")
.list();
✅ SQL
String sql = "SELECT * FROM users WHERE username = ?";
session.createNativeQuery(sql)
.setParameter(1, "john")
.list();
🔹 When to use which?
✅ HQL → recommended for most Hibernate-based CRUD and complex queries involving entities.
✅ SQL → useful when you need database-specific features (e.g., vendor functions, stored procedures) or reporting queries not easily mapped to your object model.
✅ Key takeaway:
HQL is object-oriented, portable, and designed for querying mapped entities, while SQL is table-based, database-specific, and works directly on the physical schema.