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

🔹 HQL (Hibernate Query Language)
✅ Hibernate’s own object-oriented query language.
✅ Introduced before the JPA standard existed.
✅ Very similar to JPQL in syntax, but includes Hibernate-specific features, like:

  • Support for querying Hibernate-specific features (e.g., some collection mappings).
  • Functions that might not exist in JPA (e.g., current_timestamp() in HQL but not JPQL).
    ✅ Not guaranteed to be portable across JPA providers (HQL-specific queries might fail on EclipseLink or OpenJPA).

🔹 JPQL (Java Persistence Query Language)
✅ The standardized object-oriented query language defined by JPA (Java Persistence API).
✅ Syntax and concepts are nearly identical to HQL → queries entities and their properties instead of tables.
✅ Designed to be portable across any JPA provider, e.g., Hibernate, EclipseLink, OpenJPA.
✅ Does not include Hibernate-specific extensions.

🔹 Key similarities:
✅ Both query entities, not tables.
✅ Both are object-oriented and support joins, subqueries, group by, aggregation, etc.
✅ Both use entity class names and field names instead of table and column names.


🔹 Key differences summarized:

FeatureHQLJPQL
Defined byHibernate-specificJPA specification
PortabilityNot guaranteedPortable across JPA providers
FeaturesHibernate-only extensionsLimited to JPA standard
SyntaxNearly identical to JPQLNearly identical to HQL

🔹 Example (same for both HQL and JPQL):

String query = "SELECT u FROM User u WHERE u.username = :username";
TypedQuery<User> typedQuery = entityManager.createQuery(query, User.class);
typedQuery.setParameter("username", "john");
List<User> users = typedQuery.getResultList();

🔹 When should you use which?
✅ In Hibernate-specific projects without JPA → HQL is fine.
✅ In JPA-based projects (e.g., Spring Data JPA) → always use JPQL for full portability.

HQL and JPQL are almost identical in syntax and purpose, but JPQL is the JPA-standard, portable query language; HQL is Hibernate-specific and may include non-portable features.

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

Leave a Reply

Your email address will not be published.