JPA and Hibernate Interview Guide
Entity Mapping
Section titled “Entity Mapping”Example entity:
@Entity@Datapublic class Employee {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
private String name;
private String salary;
@Version private Long version;}Annotation Reference
Section titled “Annotation Reference”| Annotation | Purpose |
|---|---|
@Entity |
Maps the class to a database table |
@Id |
Primary key |
@GeneratedValue |
Auto-generates the primary key |
@Version |
Enables optimistic locking |
How @Version Works
Section titled “How @Version Works”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.
Recommended Salary Type
Section titled “Recommended Salary Type”Instead of:
private String salary;Prefer:
private BigDecimal salary;Corresponding SQL:
salary DECIMAL(10,2)Automatic Schema Generation
Section titled “Automatic Schema Generation”Spring Boot can create or update tables automatically.
spring.jpa.hibernate.ddl-auto=updateCommon Values
Section titled “Common Values”| 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 |
Interview Questions
Section titled “Interview Questions”What is optimistic locking?
Section titled “What is optimistic locking?”Optimistic locking uses a version column to detect concurrent updates. If another transaction has already modified the row, Hibernate throws an OptimisticLockException.
Why use @Version?
Section titled “Why use @Version?”- 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.
Best Practices
Section titled “Best Practices”- Use
BigDecimalfor monetary values. - Use
@Versionfor concurrent updates. - Prefer Flyway or Liquibase for schema migrations.
- Avoid
ddl-auto=createin 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.
Key Takeaways
Section titled “Key Takeaways”@Versionenables optimistic locking.- Hibernate increments the version automatically.
ddl-auto=updateis suitable for development only.- Use migration tools for production schema management.