Java.Hibernate.Beginner.What is the difference between HQL and SQL?

🔹 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:

FeatureHQLSQL
Operates onEntities & fields (OOP)Tables & columns (DB)
PortabilityDatabase-independentVendor-dependent
TranslationConverted to SQL by HibernateSent directly to DB
Object conceptsSupports polymorphism, relationshipsNo awareness of OOP
Use caseWorks with Hibernate entitiesDirect 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.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.