Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-17

In JPA, what do @Entity and @Id mean?

Options

  1. @Entity marks a class mapped to a table; @Id marks the primary key (Correct option)
  2. @Entity is a REST controller; @Id is a URL parameter
  3. @Entity creates a bean; @Id is the id of a thread
  4. Both only change how the class is written to the logs

Answer

@Entity marks a Java class that maps to a table; @Id marks the field that is the primary key

Why

JPA (Jakarta Persistence API) is the standard for mapping Java objects to relational tables (ORM). Hibernate is the most popular implementation.

@Entity says: instances of this class are rows of a table. @Id marks the primary key field. @GeneratedValue lets the database generate it, @Column customizes a column.

Every entity needs a no-argument constructor (can be protected) because the provider creates objects by reflection.

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String email;
}

Remember

@Entity = table row object. @Id = primary key.

Key terms

Practice this question in Repaso