🔹 1️⃣ Context of your project
- JPQL is used if you’re working with JPA (
javax.persistence/jakarta.persistence), e.g.:- Your project uses JPA annotations (
@Entity,@Id, etc.). - You create queries using
EntityManager.createQuery(). - You rely on JPA-standard features like
@PersistenceContext,@Transactional.
- Your project uses JPA annotations (
HQL is used if you’re directly working with native Hibernate API, e.g.:
- Your code uses
org.hibernate.Session.createQuery(). - You don’t use JPA’s
EntityManager.
🔹 2️⃣ How you build queries
✅ JPQL
TypedQuery<User> query = entityManager.createQuery(
"SELECT u FROM User u WHERE u.username = :username", User.class);
Uses JPA EntityManager.
Always JPQL.
✅ HQL
List<User> users = session.createQuery(
"FROM User u WHERE u.username = :username", User.class).list();
Uses Hibernate Session.
Always HQL.
🔹 3️⃣ Query features
- If your queries use Hibernate-specific syntax or functions (e.g.,
index(),elements(), or certain proprietary operators), that’s HQL — JPQL won’t recognize them.
🔹 4️⃣ Are you using JPA-only annotations?
- If your project uses
javax.persistence.EntityManagerinstead oforg.hibernate.Session, you’re definitely in JPQL-land.
🔹 5️⃣ Tools & providers
- If you run your queries in Spring Data JPA repositories, your
@Querystrings are JPQL. - If you run your queries directly on Hibernate’s Session API, they’re HQL.
🔹 Bottom line:
✅ JPQL → you use JPA’s EntityManager or @Query in Spring Data JPA → fully portable.
✅ HQL → you use Hibernate’s Session API directly → Hibernate-specific.
🔹 Key takeaway:
The simplest way to know:
- EntityManager → JPQL
- Session → HQL