Which annotation is used to define a native SQL query in JPA?

Java MCQ: Which annotation is used to define a native SQL query in JPA?

a) @SQLQuery
b) @NamedNativeQuery
c) @Query
d) @NativeQuery

Answer:

b) @NamedNativeQuery

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top