liveBook · Manning

@Id

As explained in Java Persistence with Spring Data and Hibernate epub

@Id is the JPA annotation that marks a persistent property or field as an entity identifier.

@Id marks the persistent property or field that supplies an entity’s database identity. In JPA, every entity must have an identifier; without @Id, @Entity alone cannot produce a complete mapping. An identifier named id conventionally maps to an ID primary-key column when no further mapping is specified. section 5.2.2

The placement and surrounding annotations determine how the persistence framework handles the identifier:

  • Place @Id on a field to select field access; Hibernate or Spring Data JPA reads and writes the identifier directly and treats fields as persistent by default. section 5.2.2
  • Expose a getter when application code needs an identifier as a lookup handle, such as selecting an item from search results. section 5.2.2

Generated identifier on a JPA entity

@Entity public class Item { @Id @GeneratedValue(generator = "ID_GENERATOR") private Long id; public Long getId() { return id; } }

Explicit identifier mapping with Spring Data JDBC

@Table("USERS") public class User { @Id @Column("ID") private Long id; @Column("USERNAME") private String username; }

Listing 5.1 Mapped Item entity class with an identifier property
Path: Ch05/generator/src/main/java/com/manning/javapersistence/ch05/model
 /Item.java
 
@Entity
\1 Item {
    @Id
    @GeneratedValue(generator = "ID_GENERATOR")
    private Long id;
    public Long getId() {
        return id;
    }
}

Inspect the complete mapped Item entity showing @Id, generated-value configuration, a Long identifier, and a public getter. section 5.2.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains required identifiers, default ID mapping, field access, generated values, and explicit column mapping without covering composite identifiers.
Examples
Uses generated Long ids on Item and an explicitly mapped ID field on a Spring Data JDBC User.
What it assumes
Assumes a Java domain class and database table, while establishing that @Entity alone does not define database identity.
What you can do after
Apply it via JPA or Spring Data JDBC to map entity identity and support identifier-based persistence and lookup.
How it connects
Connects @Id with entity classes, @Entity, primary keys, field access, @GeneratedValue, @Column, Hibernate, and Spring Data JDBC.

Also explained in

Compare how 2 books explain @Id →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.