Java.Hibernate.Beginner.What is a primary key and how do you define it in Hibernate?

You annotate a field or getter in your entity class with @Id. Hibernate maps this to the primary key column in the database.

🔹 Basic example:

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

    private String username;

    // getters and setters
}

✅ Here:

  • The id field is the primary key, defined with @Id.
  • @GeneratedValue(...) tells Hibernate how to generate the key (e.g., identity, sequence, UUID).

🔹 Primary key options in Hibernate:
Simple primary key → one column mapped with @Id.
Composite primary key → multiple columns combined, mapped with:

  • @Embeddable + @EmbeddedId → recommended modern approach.
  • Or @IdClass → alternative but more verbose.

🔹 Composite key example:

@Embeddable
public class EnrollmentId implements Serializable {
    private Long studentId;
    private Long courseId;
}

@Entity
public class Enrollment {
    @EmbeddedId
    private EnrollmentId id;

    private String grade;
}

🔹 Important notes:
✅ You must define a primary key in every JPA/Hibernate entity → Hibernate requires it to track entities.
✅ Without a primary key, Hibernate can’t map objects reliably → you’ll get errors at runtime.

Key takeaway:
A primary key is a unique, non-null identifier for your entity’s rows.
In Hibernate, you define it with @Id (and optionally @GeneratedValue) or use @EmbeddedId/@IdClass for composite keys.

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

Leave a Reply

Your email address will not be published.