Which annotation is used to specify a query in JPA?

Java MCQ: Which annotation is used to specify a query in JPA?

a) @Query
b) @NamedQuery
c) @SQL
d) @Select

Answer:

b) @NamedQuery

Explanation:

The @NamedQuery annotation is used in JPA to specify a named query. Named queries are pre-defined, static queries that are associated with an entity and can be executed multiple times with different parameters. They are defined using the @NamedQuery annotation at the class level and are referenced by name in the application code.

Here’s an example:

@Entity
@NamedQuery(name = "Employee.findByName", query = "SELECT e FROM Employee e WHERE e.name = :name")
public class Employee {
    @Id
    private Long id;

    private String name;

    // Getters and setters
}

In this example, a named query Employee.findByName is defined using the @NamedQuery annotation. The query retrieves employees based on their name.

Named queries provide a convenient way to define reusable queries that can be executed in a type-safe manner in the application code.

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