Skip to content

JPA and Hibernate Interview Guide

Example entity:

@Entity
@Data
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String salary;
@Version
private Long version;
}
Annotation Purpose
@Entity Maps the class to a database table
@Id Primary key
@GeneratedValue Auto-generates the primary key
@Version Enables optimistic locking

Optimistic locking prevents lost updates.

sequenceDiagram
    participant UserA
    participant DB
    participant UserB

    UserA->>DB: Read Employee (version=0)
    UserB->>DB: Read Employee (version=0)

    UserA->>DB: Update Employee
    DB-->>UserA: version becomes 1

    UserB->>DB: Update Employee(version=0)
    DB-->>UserB: OptimisticLockException

Each successful update increments the version automatically.


Instead of:

private String salary;

Prefer:

private BigDecimal salary;

Corresponding SQL:

salary DECIMAL(10,2)

Spring Boot can create or update tables automatically.

spring.jpa.hibernate.ddl-auto=update
Value Purpose
none No schema generation
validate Validate schema only
update Update existing schema
create Drop and recreate tables
create-drop Recreate and remove on shutdown

Optimistic locking uses a version column to detect concurrent updates. If another transaction has already modified the row, Hibernate throws an OptimisticLockException.

  • Prevents lost updates
  • Supports concurrent users
  • Requires no explicit database locking

Why is ddl-auto=update discouraged in production?

Section titled “Why is ddl-auto=update discouraged in production?”

Schema changes should be managed using migration tools such as Flyway or Liquibase instead of automatic updates.


  • Use BigDecimal for monetary values.
  • Use @Version for concurrent updates.
  • Prefer Flyway or Liquibase for schema migrations.
  • Avoid ddl-auto=create in production.
  • Use meaningful SQL migration scripts.

For running Spring Boot against a Dockerized MySQL (service names vs localhost, the “Unable to determine Dialect” error, and table setup SQL), see the Spring Boot + Docker + MySQL guide.


  • @Version enables optimistic locking.
  • Hibernate increments the version automatically.
  • ddl-auto=update is suitable for development only.
  • Use migration tools for production schema management.