Java MCQ: Which annotation is used to define a native SQL query in JPA?
Answer:
Explanation:
The @NamedNativeQuery
annotation in JPA is used to define a native SQL query. This annotation allows you to write SQL queries that are specific to the database and execute them within the context of JPA, while still benefiting from the entity management and transaction capabilities provided by JPA.
Here’s an example:
@Entity
@NamedNativeQuery(name = "Employee.findByDepartment",
query = "SELECT * FROM employees WHERE department_id = :deptId",
resultClass = Employee.class)
public class Employee {
@Id
private Long id;
private String name;
// Getters and setters
}
In this example, a native query Employee.findByDepartment
is defined using the @NamedNativeQuery
annotation. The query retrieves employees based on their department ID.
The @NamedNativeQuery
annotation provides a way to execute complex SQL queries that cannot be expressed easily using JPQL (Java Persistence Query Language), while still mapping the results to entity classes.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html