Performance: @Id and @GeneratedValue for primary keys
This affects database interaction speed and server response time during entity creation.
Jump into concepts and practice - no test required
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@Id
private Long id; // manually assigned IDs in code| Pattern | DB Queries | Locking | Insert Latency | Verdict |
|---|---|---|---|---|
| Manual ID assignment | Extra uniqueness checks | None | High due to checks | [X] Bad |
| @GeneratedValue TABLE | Additional query per insert | Possible lock contention | Medium | [!] OK |
| @GeneratedValue IDENTITY | Single insert query | No extra locking | Low | [OK] Good |
@Id annotation in a Spring Boot entity?@Id@Id annotation marks a field as the primary key in a database entity.@GeneratedValue generates values, but @Id specifically identifies the primary key field.@Id marks primary key [OK]@GeneratedValue with GenerationType.IDENTITY in a Spring Boot entity?GenerationType.IDENTITY is used to let the database auto-increment the primary key.@GeneratedValue(strategy = GenerationType.IDENTITY).user.getId() after saving a new user to the database? @Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}user.getId() will hold the generated unique Long value assigned by the database. @Entity
public class Product {
@Id
@GeneratedValue
private Long productId;
private String name;
}@GeneratedValue annotation without specifying a strategy defaults to AUTO, which may behave differently depending on the database.user_seq. Which is the correct way to annotate the ID field?GenerationType.SEQUENCE and a matching @SequenceGenerator annotation.@SequenceGenerator defines the sequence name and allocation size, linked by the generator name in @GeneratedValue.