Junior
What types of queries can I perform using Hibernate?
sobes.tech AI
Answer from AI
Hibernate allows the following types of queries:
-
HQL (Hibernate Query Language)
- An object-oriented query language similar to SQL.
- Works with entity class and property names, not with database tables and columns.
- Cross-DBMS.
// Example of HQL query String hql = "FROM User u WHERE u.lastName = :lastName"; List<User> users = session.createQuery(hql, User.class) .setParameter("lastName", "Smith") .list(); -
JPA Criteria API
- A programmatic way to build queries via API, not strings.
- Type-safe, allows errors to be detected at compile time.
- Part of the JPA specification.
// Example of Criteria API CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> root = cq.from(User.class); cq.select(root).where(cb.equal(root.get("firstName"), "John")); List<User> users = session.createQuery(cq).getResultList(); -
Native SQL
- Allows executing native SQL queries directly to the database.
- Useful for database-specific functions or complex query optimization.
// Example of Native SQL String sql = "SELECT * FROM Users WHERE age > :minAge"; List<Object[]> results = session.createNativeQuery(sql) .setParameter("minAge", 30) .list(); // Manually convert results to entities or DTOs -
Named Queries (HQL or Native SQL)
- Predefined queries specified in metadata (annotations or XML).
- Simplify query reuse and improve code readability.
// Defining a Named Query in User entity (annotation) @NamedQuery(name = "User.findByEmail", query = "FROM User u WHERE u.email = :email") public class User { ... } // Using Named Query List<User> users = session.createNamedQuery("User.findByEmail", User.class) .setParameter("email", "test@example.com") .getResultList();
Depending on the task and required flexibility, the most suitable query method is chosen. HQL and Criteria API are preferred as they operate at the entity level and are more cross-DBMS. Native SQL is used when database-specific operations or optimization are needed.