What is the use of the @Entity annotation in Spring Data JPA?

What is the use of the @Entity annotation in Spring Data JPA?

A) To map a Java class to a database table
B) To define a primary key for the entity
C) To specify a repository interface
D) To indicate that a class is a Spring bean

Answer:

A) To map a Java class to a database table

Explanation:

The @Entity annotation in Spring Data JPA is used to map a Java class to a database table. This annotation is part of the JPA (Java Persistence API) specification and is applied to classes that represent database entities.

For example:


@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and setters
}

In this example, the User class is annotated with @Entity, indicating that it is a JPA entity. The fields of the class correspond to the columns of the database table, and the class represents the table’s rows. The @Id annotation is used to specify the primary key, and the @GeneratedValue annotation indicates that the primary key value will be generated automatically.

The @Entity annotation is fundamental in JPA, as it establishes the link between the object-oriented domain model and the relational database.

Reference links:

Spring Data JPA Tutorial

Leave a Comment

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

Scroll to Top