Home >Java >javaTutorial >How to use @Query annotation for custom query in Hibernate?
How to use @Query annotation for custom query in Hibernate? Hibernate's @Query annotation allows us to perform custom queries using JPQL or SQL. JPQL query: Add @Query annotation on entity class methods. Specify the JPQL query string. SQL queries: Use the @NamedNativeQuery annotation to define named native queries. Specify the query statement and result class. Practical example: We can find employees in a specific department using the following query: @Query("SELECT e FROM Employee e WHERE e.department = :department") Lista7c15504e26c2dc9d33fa17ec3230b5f findEmployeesInDepartment(@Param("department") String department);
Hibernate's@Query
annotation allows us to define custom JPQL or SQL queries on entity classes. It provides a convenient way to perform more advanced queries without writing low-level SQL code.
To use JPQL (Java Persistence Query Language), you need to add the @Query
annotation to the entity class method and specify the JPQL query string. For example:
@Query("SELECT e FROM Employee e WHERE e.salary > 50000") List<Employee> findEmployeesWithSalaryGreaterThan50000();
This code defines a query that returns all employees with a salary greater than 50,000.
To use native SQL query, you can use the @NamedNativeQuery
annotation. @NamedNativeQueries
Allows us to define multiple named native queries. For example:
@NamedNativeQueries({ @NamedNativeQuery( name = "findEmployeesWithSalaryGreaterThan50000", query = "SELECT * FROM Employee WHERE salary > 50000", resultClass = Employee.class ) })
This code defines a native SQL query called "findEmployeesWithSalaryGreaterThan50000", which returns all employees whose salary is greater than 50,000.
Consider such an entity class:
@Entity public class Employee { @Id private Long id; private String name; private double salary; //省略 getter 和 setter }
We can use the @Query
annotation to find all employees in a specific department:
@Query("SELECT e FROM Employee e WHERE e.department = :department") List<Employee> findEmployeesInDepartment(@Param("department") String department);
Now, we can use the findEmployeesInDepartment
method to get all the employees in a specific department as follows:
List<Employee> employees = employeeRepository.findEmployeesInDepartment("Engineering");
@Query
Annotations are a powerful tool in Hibernate that allow us to execute custom queries. We can write queries using JPQL or native SQL and use named parameters to pass query parameters dynamically.
The above is the detailed content of How to use @Query annotation for custom query in Hibernate?. For more information, please follow other related articles on the PHP Chinese website!