πŸ—„οΈ Spring Data JPA & Hibernate β€” Complete Interview Notes

Stack: Spring Boot 3.x Β· Spring Data JPA Β· Hibernate 6.x Β· PostgreSQL



1. JPA vs Hibernate vs Spring Data JPA

Conceptual Hierarchy

Spring Data JPA   (abstraction layer β€” repositories, query derivation)
      ↓
   JPA API        (javax.persistence / jakarta.persistence β€” specification)
      ↓
  Hibernate       (JPA implementation β€” actual ORM engine)
      ↓
   JDBC           (raw DB connection)
Feature JPA Hibernate Spring Data JPA
Type Specification (interface) Implementation Abstraction
Package jakarta.persistence org.hibernate org.springframework.data
Provides Annotations, JPQL HQL, Session, Caching Repositories, Query derivation
Standalone ❌ βœ… ❌ (needs JPA impl)

application.properties β€” Baseline Config

# DataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=secret
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA / Hibernate
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=validate        # prod: validate | dev: update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true

# HikariCP
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=2
spring.datasource.hikari.connection-timeout=30000

2. Entity Lifecycle & States

Four Entity States

New / Transient  ──persist()──▢  Managed / Persistent
                                        β”‚
                              flush() β†’ SQL sent to DB
                                        β”‚
                              detach() / close()
                                        ↓
                                    Detached  ──merge()──▢  Managed

Managed ──remove()──▢  Removed  ──commit()──▢  Deleted from DB
State In PersistenceContext DB Row Exists Changes Tracked
Transient ❌ ❌ ❌
Managed βœ… βœ… (after flush) βœ… (dirty check)
Detached ❌ βœ… ❌
Removed βœ… βœ… (until commit) βœ…

Code Example

@Service
@Transactional
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public void demonstrateLifecycle() {
        // TRANSIENT β€” no ID, not tracked
        User user = new User("Aditya", "[email protected]");

        // MANAGED β€” tracked by persistence context
        em.persist(user);

        // Dirty checking β€” no explicit save needed!
        user.setEmail("[email protected]"); // UPDATE will be issued at flush

        // DETACHED
        em.detach(user);
        user.setEmail("[email protected]"); // NOT tracked

        // Back to MANAGED
        User mergedUser = em.merge(user);

        // REMOVED
        em.remove(mergedUser);
    }
}

⚠️ Key Interview Point: In Spring Data JPA, save() calls persist() for new entities and merge() for detached ones. It checks id == null OR @Version field.