Java.Hibernate.Beginner.What is the @Id annotation used for?

The @Id annotation marks a field or getter in a JPA entity as the primary key, meaning it uniquely identifies each entity instance and maps to the primary key column in the database table.

🔹 Why is it important?
✅ Every JPA entity must have exactly one primary key → it’s required for Hibernate or any JPA provider to:

  • Track and manage entities in the persistence context.
  • Generate correct SQL for CRUD operations.
  • Identify objects for updates, deletes, and relationships.
    ✅ Without an @Id, your entity is invalid and won’t work with JPA/Hibernate → you’ll get runtime errors.

🔹 Basic example:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // optional, for auto-increment
    private Long id;

    private String username;
}

✅ Here:

  • id is the primary key column in the users table.
  • Hibernate uses id as the unique identifier of each User instance.

🔹 Where can you put @Id?
✅ On a field (as above) → field access.
✅ On a getter method:

@Id
public Long getId() { return id; }

🔹 What about key generation?
You often combine @Id with @GeneratedValue to let Hibernate automatically generate key values:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;

🔹 For composite keys:
If your primary key spans multiple columns, use @EmbeddedId or @IdClass, but each key field still uses @Id in case of @IdClass.

Key takeaway:
@Id marks the primary key field of an entity → it’s essential for Hibernate/JPA to uniquely identify, persist, and manage entity instances.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.