Stack: Spring Boot 3.x Β· Spring Data JPA Β· Hibernate 6.x Β· PostgreSQL
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) |
# 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
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) | β |
@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()callspersist()for new entities andmerge()for detached ones. It checksid == nullOR@Versionfield.