Skip to lesson

@Entity, @Table, @Id and @GeneratedValue

A ShopLite service wants to work with Product objects, but the data sits as rows in a MySQL table. Writing SQL and copying every column by hand for each query is slow and easy to get wrong.

Entity rules: @Entity, a no-arg constructor and a non-final class

An entity is a Java class marked with @Entity whose objects stand for the rows of one database table. Hibernate loads a row into an entity object and saves a new or changed entity back as an INSERT or UPDATE.

@Entity marks the class, @Id marks the key field, and a no-arg constructor lets Hibernate create the objects. Example 1 is the ShopLite Product.

A Product entity maps to the products table, field by field. The id field maps to the product_id column, and it needs the @Column name because the names differ. The sku field maps to the sku column. The categoryId field maps to category_id by Spring Boot snake case naming, with no annotation.

Example 1 · src/main/java/com/shoplite/product/Product.java

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Product.javaJava
package com.shoplite.product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity@Table(name = "products")public class Product {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "product_id")    private Integer id;
    private String sku;    private String name;    private Integer categoryId;     // a plain column until the Relationships module    private BigDecimal price;    private int stock;
    protected Product() {        // for Hibernate only    }
    public Product(String sku, String name, Integer categoryId, BigDecimal price, int stock) {        this.sku = sku;        this.name = name;        this.categoryId = categoryId;        this.price = price;        this.stock = stock;    }
    public Integer getId() { return id; }    public String getSku() { return sku; }    public String getName() { return name; }    public Integer getCategoryId() { return categoryId; }    public BigDecimal getPrice() { return price; }    public int getStock() { return stock; }}
Sample output
INFO ... org.hibernate.orm.core                   : HHH000001: Hibernate ORM core version 7.4.5.Final
INFO ... com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO ... j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
INFO ... com.shoplite.ShopliteLabApplication      : Started ShopliteLabApplication in 12.014 seconds (process running for 13.235)

What this code does

  • @Entity plus @Table(name = "products") map the class to the ShopLite table; @Id, @GeneratedValue and @Column(name = "product_id") map the key. The other fields need no annotation because their names match after snake case (categoryId -> category_id).
  • The protected no-arg constructor is for Hibernate; your code uses the five-argument one. There are getters but no setters: Hibernate fills fields directly.
  • The log shows the app started with ddl-auto: validate, so the table has every mapped column with a matching type. is_active is not mapped yet; MySQL fills its default when Hibernate inserts.

Example 2 · A simplified model of how Hibernate builds an entity

HowHibernateBuildsDemo.javaJava
import java.lang.reflect.Constructor;import java.lang.reflect.Field;
class Product {    private Integer id;    private String sku;
    protected Product() {    }
    public Product(String sku) {        this.sku = sku;    }
    public String toString() {        return "Product[id=" + id + ", sku=" + sku + "]";    }}
record ProductRecord(Integer id, String sku) {}
public class HowHibernateBuildsDemo {
    // Roughly what Hibernate does with a row: make an empty object, then fill each field    static Object buildFromRow(Class<?> type, Object id, Object sku) throws Exception {        Constructor<?> noArgs = type.getDeclaredConstructor();   // needs a no-arg constructor        noArgs.setAccessible(true);        Object entity = noArgs.newInstance();
        Field idField = type.getDeclaredField("id");        idField.setAccessible(true);        idField.set(entity, id);
        Field skuField = type.getDeclaredField("sku");        skuField.setAccessible(true);        skuField.set(entity, sku);        return entity;    }
    public static void main(String[] args) throws Exception {        System.out.println(buildFromRow(Product.class, 1, "MOB-RN13"));
        try {            buildFromRow(ProductRecord.class, 1, "MOB-RN13");        } catch (NoSuchMethodException e) {            System.out.println("Record: no no-arg constructor -> " + e.getClass().getSimpleName());        }    }}
Output
Product[id=1, sku=MOB-RN13]
Record: no no-arg constructor -> NoSuchMethodException

What this code does

  • A simplified model, using plain Java reflection: make an empty object with the no-arg constructor, then set private fields one by one. Hibernate does the same kind of work (with more caching and checks) for every row it loads.
  • protected Product() is enough, because setAccessible(true) opens it. The record has only its canonical constructor, so getDeclaredConstructor() throws NoSuchMethodException.

Example 3 · A record as an entity: starts, then fails on the first load

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Product.javaJava
package com.shoplite.product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity@Table(name = "products")public record Product(        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "product_id") Integer id,        String sku,        String name,        Integer categoryId,        BigDecimal price,        int stock) {}
// In the runner:// Product redmi = products.findById(1).orElseThrow();
Sample output
INFO ... com.shoplite.ShopliteLabApplication      : Started ShopliteLabApplication in 9.462 seconds (process running for 10.532)
DEBUG ... org.hibernate.SQL                        : select p1_0.product_id,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
ERROR ... o.s.boot.SpringApplication               : Application run failed
org.springframework.orm.jpa.JpaSystemException: No default constructor for entity 'com.shoplite.product.Product'

What this code does

  • Hibernate 7 accepts the mapping at startup, and the SELECT even runs. The failure comes when it tries to create the object for the row: a record has no no-arg constructor.
  • This is worse than a startup error: the bug hides until the first request that loads a product. Even with an extra no-arg constructor, a record's fields are final, so Hibernate could not fill or change them.
  • Records are still perfect for DTOs and for @Embeddable value objects, which the Embedded value objects lesson shows.

The rules, each with its reason:

  • @Entity on a top-level class, plus an @Id field. Without @Entity, a repository for the class fails to start.
  • A protected or public no-arg constructor (a constructor with no parameters). Hibernate calls it when it loads a row and then fills each field from a column. protected keeps your own code on the real constructor that sets every required field.
  • Not final, and no final mapped fields. Hibernate sometimes creates a subclass of your entity at runtime (a proxy, covered in the equals and hashCode lesson) and changes field values after loading.
  • A record breaks all of these: it has no no-arg constructor, it is final, and its fields are final. A record cannot be an entity (Example 3).
Every example in this module runs in a small practice project, mapping-lab: the Module 1 setup (the JPA starter, the MySQL driver, ddl-auto: validate, SQL logging) against the ShopLite database, with one small CommandLineRunner per demo.

@Table and Spring's default naming

A naming strategy is the rule that turns a Java name into a table or column name. Spring Boot uses snake case: every capital letter becomes an underscore plus the lowercase letter, so unitPrice maps to unit_price.

@Table(name = "products") tells Hibernate which table the entity maps to. Without it, the class name decides: Product becomes product, and Example 4 shows what that breaks.

Example 4 · Without @Table: the table name comes from the class name

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Product.javaJava
@Entity                      // no @Table: Hibernate looks for a table named "product"public class Product {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "product_id")    private Integer id;    // ... the same fields as Example 1}
Sample output
ERROR ... j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory  [persistence unit: default] ; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [product]
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [product]

What this code does

  • The class Product became the table name product. ShopLite's table is products, so validate refuses to start the app.
  • The fix is one line: @Table(name = "products"). Name the table on every entity, even when the default would match, so a class rename never silently points at another table.

Column names follow the naming strategy with no annotation: categoryId maps to category_id, as the SQL of Example 5 shows. When the database name does not follow the rule, name it yourself: the id field id reads the column product_id, so it gets @Column(name = "product_id"). The next lesson covers @Column fully.

Predict the output

Which name does Hibernate use?

Spring Boot snake case is on. Pick the table or column name.

Round 1 of 3

Which column does the field unitPrice read?

@Entity
@Table(name = "order_items")
public class OrderItem {
private int quantity;
private BigDecimal unitPrice;
}
With ddl-auto: validate, a wrong table name stops the app at startup instead of failing later on the first query. That is why ShopLite validates.

@Id and @GeneratedValue(strategy = IDENTITY)

IDENTITY is the id strategy where the database creates the primary key itself. With MySQL, AUTO_INCREMENT fills the key during the INSERT, and Hibernate reads it back into the object.

@Id marks the primary key field, and @GeneratedValue(strategy = GenerationType.IDENTITY) lets MySQL create the key. Example 5 saves a new product and shows the id appear.

Example 5 · ProductRepository and a runner: the ids and the SQL

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

ProductRepository.javaJava
// src/main/java/com/shoplite/product/ProductRepository.javapackage com.shoplite.product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> {}
// src/main/java/com/shoplite/product/ProductDemoRunner.javapackage com.shoplite.product;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Componentclass ProductDemoRunner implements CommandLineRunner {
    private final ProductRepository products;
    ProductDemoRunner(ProductRepository products) {        this.products = products;    }
    @Override    public void run(String... args) {        Product redmi = products.findById(1).orElseThrow();        System.out.println("Loaded: " + redmi.getSku() + " | " + redmi.getName() + " | Rs " + redmi.getPrice());
        Product keyboard = new Product("ACC-KB100", "Zebronics Wireless Keyboard", 4, new BigDecimal("999.00"), 30);        System.out.println("Before save, id = " + keyboard.getId());        Product saved = products.save(keyboard);        System.out.println("After save, id = " + saved.getId());    }}
Sample output
DEBUG ... org.hibernate.SQL                        : select p1_0.product_id,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
Loaded: MOB-RN13 | Redmi Note 13 5G | Rs 17999.00
Before save, id = null
DEBUG ... org.hibernate.SQL                        : insert into products (category_id,name,price,sku,stock) values (?,?,?,?,?)
After save, id = 16

What this code does

  • JpaRepository<Product, Integer> names the entity and its id type. findById(1) produced the SELECT: note category_id from the field categoryId, and the alias p1_0 Hibernate gives the table.
  • The INSERT has no product_id: with IDENTITY, MySQL creates the key and Hibernate puts it into the same keyboard object, so saved.getId() is 16 on a fresh ShopLite database.
  • The values appear as ?: Hibernate always binds values as parameters, like the PreparedStatement code from the JDBC section. The next module covers the repository methods in depth.

A new Product has id == null before save() and a real id after it, and the INSERT Hibernate writes has no product_id column at all. Use a wrapper type (Integer, not int) so "no id yet" can be null, and match the column type: ShopLite's keys are INT, so the field is Integer and the repository is JpaRepository<Product, Integer>. A Long id against an INT column fails validation with wrong column type encountered in column [product_id] (shown in the next lesson).

The strategies to know:

  • IDENTITY: the database's auto-increment, the right choice for MySQL.
  • AUTO (the default when you write only @GeneratedValue): on MySQL, Hibernate 7 picks a sequence kept in a table, so validation fails with Schema validation: missing table [products_seq].
  • SEQUENCE: for databases with real sequences, such as PostgreSQL or Oracle.
A switch from Section 15: the JdbcClient repositories there used Long ids, because JDBC happily reads an INT into a long. Hibernate's validate is stricter, so from this module on every ShopLite entity, repository and service uses Integer ids, exactly matching the INT columns. Foreign keys such as categoryId stay plain Integer columns until the Relationships module turns them into links.

Field access vs property access

Field access means Hibernate reads and writes the fields of an entity directly, because @Id sits on a field. Hibernate then ignores getters and setters, so an id can have a getter and no setter.

Put @Id on a getter instead of a field and Hibernate switches to property access: it goes through getters and setters, as in the snippet.

Java
// Property access: @Id on the getter (avoid this in ShopLite)@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "product_id")public Integer getId() { return id; }
// Startup fails: no setId(...) exists// PropertyNotFoundException: Could not locate setter method//   for property 'id' of class 'com.shoplite.product.Product'

With property access, every getter is treated as a mapped column and needs a matching setter. Without setId, the app does not start: Could not locate setter method for property 'id' of class 'com.shoplite.product.Product'.

Use field access, as all ShopLite entities do. The id then has only a getter, so nobody outside Hibernate can change a row's primary key by mistake, and setters exist only where a change makes business sense (deactivate(), not setActive(...)).

Startup errors: "no identifier" and "Not a managed type"

Two startup errors point at a broken entity definition. Example 6 shows both messages.

Example 6 · Two startup errors: no @Id, and an entity outside the scanned packages

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Text
1) @Id and @GeneratedValue removed from Product.id2) Product moved to the package com.catalog,   while the main class is com.shoplite.ShopliteLabApplication   and ProductRepository stays in com.shoplite.product
Sample output
1)
ERROR ... j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Entity 'com.shoplite.product.Product' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)
...
Caused by: org.hibernate.AnnotationException: Entity 'com.shoplite.product.Product' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)

2)
ERROR ... o.s.boot.SpringApplication               : Application run failed
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository' defined in com.shoplite.product.ProductRepository defined in @EnableJpaRepositories declared on DataJpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.catalog.Product
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.catalog.Product

What this code does

  • Error 1 comes from Hibernate itself (AnnotationException) while it reads the entity classes. The message names the class and the fix: add @Id.
  • Error 2 comes from Spring Data: productRepository cannot be built because com.catalog.Product was never scanned as an entity. Move the class under com.shoplite.

Entity '...' has no identifier means an @Entity class has no @Id field. Hibernate 7 checks this while building the entity manager factory, so the app stops at startup (older versions said No identifier specified for entity). Add @Id to the primary key field.

Not a managed type: class ... means a repository names a class that Hibernate never registered as an entity: the class has no @Entity, or it sits outside the packages Spring Boot scans (the main class's package and everything below it, so an entity in com.catalog is never found). Read the last Caused by: line of a startup failure first: it holds the real reason.

Fix the error

Fix the entity from its startup error

Read the error, then pick the line that replaces the marked line.

Round 1 of 3

The app stops at startup. Fix line 4.

@Entity
@Table(name = "products")
public class Product {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String sku;
}

Error

Entity 'com.shoplite.product.Product' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)

Next step

Check your understanding

11 quick questions