Querying the Database
In Hibernate, you can execute queries using the Hibernate Query Language (HQL), which is similar to SQL but operates on entity objects instead of database tables.
To execute a query in Hibernate, you can use the createQuery()
method of the Session
class. This method takes an HQL query string as a parameter and returns a Query
object that can be used to retrieve the results.
Here is an example of executing a query to retrieve employees with a salary greater than $5000:
1const query = "SELECT e FROM Employee e WHERE e.salary > 5000";
2
3List<Employee> employees = session.createQuery(query).getResultList();
4
5for (Employee employee : employees) {
6 System.out.println(employee.getFirstName() + " " + employee.getLastName());
7}
In the above example, we create an HQL query string to select employees whose salary is greater than $5000. We then use the createQuery()
method to create a query object, getResultList()
to execute the query and retrieve the result as a list of Employee
objects.
We can then iterate over the list and print the first name and last name of each employee.
HQL provides a rich set of features for querying entities, including filtering, sorting, and aggregation. It also supports joins and subqueries to retrieve data from multiple entities or perform complex operations.
Using HQL, you can leverage the power of object-oriented querying to interact with your database and retrieve the data you need.
xxxxxxxxxx
const query = "SELECT e FROM Employee e WHERE e.salary > 5000";
List<Employee> employees = session.createQuery(query).getResultList();
for (Employee employee : employees) {
System.out.println(employee.getFirstName() + " " + employee.getLastName());
}