Q64Advanced Boot
How do you debug auto-configuration?
Use the condition evaluation report, startup logs, and dependency tree to determine why configuration matched or backed off
Answer
Use the condition evaluation report, startup logs, and dependency tree to determine why configuration matched or backed off. Verify properties, classpath, candidate beans, and framework compatibility.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
java -jar app.jar --debug
./mvnw dependency:tree
Key Points
- Do not exclude auto-config first
- Add a regression test
Q65Advanced Boot
How do you resolve circular dependencies?
A circular dependency means components require each other directly or indirectly
Answer
A circular dependency means components require each other directly or indirectly. Prefer separating responsibilities or introducing a shared collaborator rather than hiding the cycle with lazy resolution.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
AService → BService → AService
Refactor: AService → SharedPolicy ← BService
Key Points
- Constructor cycles often block startup
- @Lazy can mask coupling
Q66Advanced Boot
How would you build a custom starter?
A reusable starter combines dependency convenience with conditional auto-configuration
Answer
A reusable starter combines dependency convenience with conditional auto-configuration. It should be property-driven, overridable by user beans, and tested for activation and back-off behavior.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
starter → auto-configuration → @ConditionalOnClass / @ConditionalOnProperty / @ConditionalOnMissingBean
Key Points
- Separate dependencies and configuration when useful
- Test conditions
Q67Production
How does graceful shutdown work?
Graceful shutdown stops new work and gives in-flight requests a bounded time to finish
Answer
Graceful shutdown stops new work and gives in-flight requests a bounded time to finish. Coordinate server settings, orchestrator termination grace, and recovery for unfinished jobs.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=20s
Key Points
- Drain readiness before termination
- Persist durable work
Q68Performance
Can Spring Boot use virtual threads?
Supported Java and Spring Boot versions can use virtual threads to reduce the cost of many blocking tasks
Answer
Supported Java and Spring Boot versions can use virtual threads to reduce the cost of many blocking tasks. They do not speed up CPU-bound work or remove database and downstream limits.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
spring.threads.virtual.enabled=true
Key Points
- Verify exact version support
- Monitor pools and downstream concurrency
Q69Resilience
How does a circuit breaker help?
A circuit breaker temporarily rejects calls when a dependency is failing or slow, limiting resource exhaustion and allowing recovery
Answer
A circuit breaker temporarily rejects calls when a dependency is failing or slow, limiting resource exhaustion and allowing recovery. It must be paired with timeouts, sensible fallback behavior, and monitoring.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Closed → failures threshold → Open → timed wait → Half-open probes
Key Points
- Retries can amplify load
- Do not fake success for critical operations
Q70Resilience
How should retries use backoff?
Retry only likely transient failures, cap attempts, add exponential backoff with jitter, and respect deadlines
Answer
Retry only likely transient failures, cap attempts, add exponential backoff with jitter, and respect deadlines. Side-effecting operations must be idempotent or protected by idempotency keys.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
delay = min(maxDelay, initialDelay × 2^attempt) + jitter
Key Points
- Do not retry validation errors
- Avoid synchronized retry storms
Q71Resilience
How would you rate-limit an API?
Rate limiting caps request volume over a time window or token budget, often by user, tenant, or API key
Answer
Rate limiting caps request volume over a time window or token budget, often by user, tenant, or API key. It can run at a gateway or in the application.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Request → identify client → token bucket → allow or HTTP 429
Key Points
- Distributed deployments need shared/partitioned state
- Return useful retry guidance
Q72Distributed systems
Explain the transactional outbox pattern.
The business change and event record are written in the same database transaction
Answer
The business change and event record are written in the same database transaction. A publisher later sends pending events to a broker, avoiding the dual-write gap between database commit and message publication.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Transaction: update order + insert outbox row → commit → publisher → broker → idempotent consumer
Key Points
- Consumers must tolerate duplicates
- Monitor lag and poison events
Q73Distributed systems
What is a saga?
A saga coordinates local transactions across services with compensating business actions
Answer
A saga coordinates local transactions across services with compensating business actions. It is useful when a global ACID transaction is impractical, but partial completion and compensation failures must be modeled.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Reserve stock → charge payment → ship
Failure → compensate earlier steps
Key Points
- Choreography vs orchestration
- Make steps idempotent
Q74Messaging
How should Spring Boot integrate with Kafka?
Spring for Apache Kafka provides producers, listeners, serializers, and error-handling integration
Answer
Spring for Apache Kafka provides producers, listeners, serializers, and error-handling integration. Reliable processing requires deliberate partitioning, consumer groups, retry policies, and idempotent effects.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
@KafkaListener(topics="orders", groupId="billing")
void consume(OrderCreated event) { service.process(event); }
Key Points
- Choose keys for ordering needs
- Plan dead-letter handling
Q75Messaging
What does exactly-once mean?
Exactly-once is scoped, not universal
Answer
Exactly-once is scoped, not universal. A broker may provide transactional guarantees within its boundaries, while external side effects still require idempotency, deduplication, or coordination.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
At-least-once delivery + idempotent handler → one effective business outcome
Key Points
- Define the guarantee boundary
- Expect redelivery after failures
Q76Security
OAuth 2.0 vs OpenID Connect
OAuth 2.0 is an authorization framework; OpenID Connect adds an identity layer
Answer
OAuth 2.0 is an authorization framework; OpenID Connect adds an identity layer. Access tokens authorize API access, while ID tokens convey authentication information to the client.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Client → OIDC provider → ID token
Client → API with access token → resource server
Key Points
- Do not use ID tokens as API access tokens
- Validate issuer, audience, expiry, signature
Q77Security
How should production secrets be managed?
Use a secret manager or secure deployment mechanism, least-privilege access, rotation, and auditing
Answer
Use a secret manager or secure deployment mechanism, least-privilege access, rotation, and auditing. Never hard-code secrets in repositories, image layers, logs, or public management endpoints.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Application identity → secret manager → credential
Key Points
- Separate environments
- Plan rotation without downtime
- Scan build artifacts
Q78Security
How do you prevent SSRF?
Server-side request forgery can make a service fetch unintended destinations
Answer
Server-side request forgery can make a service fetch unintended destinations. Allowlist destinations, validate resolved IPs, restrict redirects, and enforce outbound network controls.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Untrusted URL → host/IP policy → restricted HTTP client
Key Points
- Block private and metadata destinations where appropriate
- Account for DNS rebinding
Q79Security
What is mass assignment?
Mass assignment happens when client input is bound directly to sensitive model fields, allowing changes such as role or owner
Answer
Mass assignment happens when client input is bound directly to sensitive model fields, allowing changes such as role or owner. Use explicit DTOs and authorize changes in business logic.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
JSON → allowlisted DTO → authorized service update
Key Points
- Never trust client-supplied roles
- Test privileged-field tampering
Q80Persistence
Optimistic vs pessimistic locking
Optimistic locking detects conflicts on update and suits lower contention
Answer
Optimistic locking detects conflicts on update and suits lower contention. Pessimistic locking obtains database locks to serialize critical concurrent operations but can reduce throughput and cause deadlocks.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Low contention → @Version
High critical contention → short locked transaction
Key Points
- Measure contention
- Keep lock transactions short
- Handle timeouts
Q81Performance
How do you size a connection pool?
Pool size depends on database capacity, concurrency, query duration, and replica count
Answer
Pool size depends on database capacity, concurrency, query duration, and replica count. Increasing it blindly can overload the database; inspect acquisition wait, active connections, leaks, and slow queries.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Potential connections = pool size × replica count
Key Points
- Budget all application replicas
- Monitor pool and database metrics
Q82Concurrency
How do you prevent thread-pool exhaustion?
Use bounded executors and queues, request deadlines, admission control, and predictable overload rejection
Answer
Use bounded executors and queues, request deadlines, admission control, and predictable overload rejection. Unbounded queues can hide overload until latency and memory usage become unacceptable.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Incoming work → bounded queue → worker pool; full → reject/shed load
Key Points
- Monitor queue depth
- Size for workload
- Propagate deadlines
Q83Observability
How do you investigate a memory leak?
Track heap after garbage collection, inspect allocations, capture a protected heap dump, and identify unexpectedly retained objects
Answer
Track heap after garbage collection, inspect allocations, capture a protected heap dump, and identify unexpectedly retained objects. Common causes include unbounded caches and static collections.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Metrics → heap dump/profile → retained-object analysis → fix → regression test
Key Points
- Use JFR or heap tools
- Heap dumps may contain sensitive data
Q84Performance
How can startup time be improved?
Measure startup first, then reduce unnecessary bean creation, auto-configuration, and blocking initialization
Answer
Measure startup first, then reduce unnecessary bean creation, auto-configuration, and blocking initialization. Lazy initialization can help selectively, but readiness must not be declared before the service can safely serve traffic.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Measure → identify slow initializer → optimize → remeasure
Key Points
- Compare cold starts consistently
- Keep health-critical initialization
Q85Architecture
How would you design multi-tenancy?
Tenancy can use shared tables with tenant keys, schema-per-tenant, or database-per-tenant
Answer
Tenancy can use shared tables with tenant keys, schema-per-tenant, or database-per-tenant. Choose based on isolation, compliance, scale, and operational cost, and enforce tenant scope centrally.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Authenticated request → tenant context → authorization → tenant-scoped repository
Key Points
- Derive tenant from trusted identity
- Tenant-aware cache keys
- Plan migrations
Q86Observability
How do distributed traces help?
Distributed tracing links spans across services using trace context, helping locate latency and failures
Answer
Distributed tracing links spans across services using trace context, helping locate latency and failures. Metrics show aggregate patterns and logs provide event detail.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Gateway span → Order span → Payment span → Database span
Key Points
- Propagate context
- Avoid high-cardinality metric labels
- Protect sensitive trace attributes
Q87Deployment
Blue-green vs canary deployment
Blue-green switches traffic between two environments and supports fast rollback if data changes are compatible
Answer
Blue-green switches traffic between two environments and supports fast rollback if data changes are compatible. Canary gradually routes a small percentage to a new version and expands based on health signals.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Blue 100% → Green 100%
Canary: stable 95% + new 5% → gradual expansion
Key Points
- Database compatibility matters
- Set rollback thresholds
Q88Deployment
How do you containerize Spring Boot?
Package the application in a minimal supported runtime image, use a non-root user, externalize configuration, and avoid secrets in image layers
Answer
Package the application in a minimal supported runtime image, use a non-root user, externalize configuration, and avoid secrets in image layers. Pin and scan base images.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/app.jar app.jar
USER 10001
ENTRYPOINT ["java","-jar","app.jar"]
Key Points
- Use reproducible builds
- Configure resource limits and graceful shutdown
Q89Deployment
How should Kubernetes probes be configured?
Liveness determines whether a process should restart; readiness determines whether it should receive traffic
Answer
Liveness determines whether a process should restart; readiness determines whether it should receive traffic. A startup probe can protect slow initialization from premature liveness failure.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
Key Points
- Do not overuse deep dependency checks
- Align probe thresholds with startup behavior
Q90Architecture
How would you apply clean architecture?
Clean architecture keeps domain rules and use cases independent of infrastructure details
Answer
Clean architecture keeps domain rules and use cases independent of infrastructure details. HTTP, persistence, and messaging adapters depend inward on stable interfaces rather than making business logic depend on framework specifics.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
HTTP adapter → use case → domain
↑
repository port ← persistence adapter
Key Points
- Keep framework types near edges when practical
- Avoid layers without purpose
Q91Architecture
What is hexagonal architecture?
Ports-and-adapters architecture exposes application capabilities through ports and implements them with adapters for HTTP, databases, or messaging
Answer
Ports-and-adapters architecture exposes application capabilities through ports and implements them with adapters for HTTP, databases, or messaging. This lets tests or alternate transports exercise the same use cases.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
REST adapter → inbound port → application core → outbound port → DB adapter
Key Points
- Ports express required capabilities
- Adapters contain infrastructure details
Q92Production
What is a production-readiness checklist?
Review correctness, security, resilience, observability, performance, deployment, and recovery
Answer
Review correctness, security, resilience, observability, performance, deployment, and recovery. Check authorization, timeouts, probes, migrations, alerts, rollback, and load-tested resource limits.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Code/tests → security review → load/failure tests → deploy → observe → rollback if needed
Key Points
- Test failure paths
- Protect sensitive logs
- Document operations
Q93Setup and configuration
How do you plan a Spring Boot major upgrade?
Review Java compatibility, migration notes, dependency versions, deprecated APIs, security changes, and runtime behavior
Answer
Review Java compatibility, migration notes, dependency versions, deprecated APIs, security changes, and runtime behavior. Upgrade in a branch, run integration tests and representative workloads, then deploy with monitoring and rollback.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Inventory → compatibility review → upgrade → test → canary → full rollout
Key Points
- Read official migration notes
- Test serialization, security, persistence, and startup
Q94REST APIs
How would you design a maintainable REST API?
Define resource routes, DTOs, validation, status codes, pagination, error formats, authentication, and compatibility rules
Answer
Define resource routes, DTOs, validation, status codes, pagination, error formats, authentication, and compatibility rules. Keep controllers thin, business logic in services, and test both contract and persistence behavior.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Client → security → controller/validation → service → repository → DB
Key Points
- Document contracts
- Apply authorization and rate limits
- Add observability
Q95Distributed systems
Why are distributed transactions difficult?
Independent services cannot normally share one local database transaction
Answer
Independent services cannot normally share one local database transaction. Partial failures and network partitions require explicit consistency choices, often using sagas, outbox events, idempotency, and reconciliation.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Service A commit → outbox/event → Service B commit
Failure → retry / compensate / reconcile
Key Points
- Define consistency requirements
- Build recovery paths
Q96Resilience
Rate limiting vs backpressure
Rate limiting caps client request volume
Answer
Rate limiting caps client request volume. Backpressure communicates or enforces downstream capacity so producers do not overwhelm consumers; both may be needed at different boundaries.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Client → rate limiter → service → bounded queue → consumer
Key Points
- 429 can signal rate limits
- Bound queues
- Monitor rejection and latency
Q97Testing
What is contract testing?
Contract testing verifies that a provider and consumer agree on HTTP or message expectations without always requiring a full end-to-end environment
Answer
Contract testing verifies that a provider and consumer agree on HTTP or message expectations without always requiring a full end-to-end environment. It complements integration and end-to-end testing.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Consumer expectation → provider verification → CI gate
Key Points
- Use realistic contracts
- Test backward compatibility
- Version event schemas
Q98Performance
How do you load-test a Spring Boot API?
Define representative traffic, data volume, concurrency, and success criteria
Answer
Define representative traffic, data volume, concurrency, and success criteria. Measure throughput, p95/p99 latency, errors, CPU, memory, pools, and database behavior while ramping load and testing recovery.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Baseline → ramp → sustain → spike/recovery → analyze bottleneck
Key Points
- Use realistic data
- Measure tail latency
- Protect shared environments
Q99Distributed systems
What is eventual consistency?
Eventual consistency means separate services or replicas may temporarily disagree but converge if updates stop and propagation succeeds
Answer
Eventual consistency means separate services or replicas may temporarily disagree but converge if updates stop and propagation succeeds. APIs should communicate pending operations and expose status rather than promise immediate downstream completion.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Command accepted → pending → event propagation → state converges
Key Points
- Define acceptable delay
- Support retries and reconciliation
Q100Deployment
How should feature flags be used?
Feature flags separate deployment from activation, enabling controlled rollout and rapid disablement
Answer
Feature flags separate deployment from activation, enabling controlled rollout and rapid disablement. Define safe defaults, ownership, monitoring, and cleanup because stale flags add complexity.
Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.
Syntax
Deploy disabled → internal users → canary → expand → remove flag
Key Points
- Plan behavior if flag service fails
- Remove temporary flags
Q104Concurrency
What is the difference between synchronized and ReentrantLock?
What is the difference between synchronized and ReentrantLock?
Answer
Both provide mutual exclusion. synchronized uses language-level monitor locking and releases automatically when leaving the block; ReentrantLock offers features such as timed/interruptible acquisition and optional fairness.
Syntax
lock.lock(); try { ... } finally { lock.unlock(); }
Example
Use an atomic counter or a lock when multiple threads update shared state.
Code example
private final Lock lock = new ReentrantLock();
void update() { lock.lock(); try { state++; } finally { lock.unlock(); } }
Diagram
thread A/B -> lock -> critical section -> unlock
Key Points
- Always unlock in finally
- choose the simpler synchronized construct unless extra lock features are needed.
Q105Concurrency
What is a race condition?
What is a race condition?
Answer
A race condition occurs when the result depends on the unpredictable timing or interleaving of concurrent operations on shared state.
Syntax
synchronized (mutex) { counter++; }
Example
Use an atomic counter or a lock when multiple threads update shared state.
Code example
private final AtomicInteger counter = new AtomicInteger();
int next() { return counter.incrementAndGet(); }
Diagram
threads -> shared state -> unsynchronized interleaving -> unpredictable result
Key Points
- Compound operations such as read-modify-write are not automatically atomic.
Q106Concurrency
When should you use CompletableFuture?
When should you use CompletableFuture?
Answer
Use CompletableFuture to compose asynchronous tasks, combine results, and handle completion or errors without manually coordinating threads.
Syntax
CompletableFuture.supplyAsync(...).thenApply(...).exceptionally(...)
Example
Use an atomic counter or a lock when multiple threads update shared state.
Code example
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> loadName(), executor)
.thenApply(String::trim);
Diagram
task A -> thenApply -> result
\-> exceptionally -> recovery
Key Points
- Choose an appropriate executor for blocking work
- do not assume every async task should use the common pool.
Q113Spring Boot
How should secrets be managed in a Spring Boot application?
How should secrets be managed in a Spring Boot application?
Answer
Keep secrets out of source code and version control. Inject them from a secret manager or deployment environment, rotate them, and limit access.
Example
Bind deployment-specific settings through configuration rather than hardcoding them.
Code example
spring:
datasource:
password: ${DB_PASSWORD}
Diagram
secret manager -> deployment injection -> application configuration
Key Points
- Avoid logging credentials
- use separate credentials per environment and least-privilege database accounts.
Q117Hibernate & JPA
What is the difference between optimistic and pessimistic locking?
What is the difference between optimistic and pessimistic locking?
Answer
Optimistic locking detects conflicting updates, commonly with @Version. Pessimistic locking obtains a database lock to restrict concurrent access while a transaction proceeds.
Syntax
@Version private long version;
Example
Inspect SQL and transaction boundaries when tuning persistence behavior.
Code example
@Entity
class Inventory { @Id Long id; @Version long version; int quantity; }
Diagram
read version -> update with version predicate -> conflict detected if stale
Key Points
- Optimistic locking suits many low-contention cases
- use pessimistic locking only when contention and transaction design justify it.
Q121REST APIs
How do you version a REST API?
How do you version a REST API?
Answer
Common strategies include URI versioning, custom headers, and media-type versioning. Choose one strategy, document compatibility rules, and provide a migration path.
Example
Validate request DTOs and return a consistent error body.
Code example
@RequestMapping("/api/v1/orders")
@RestController
class OrderController { }
Diagram
client v1 -> stable contract; client v2 -> new contract
Key Points
- Avoid breaking existing clients without a clear deprecation and migration plan.
Q122Observability
What is the role of Actuator in Spring Boot?
What is the role of Actuator in Spring Boot?
Answer
Spring Boot Actuator exposes operational endpoints such as health and metrics, with exposure controlled by configuration and security.
Syntax
management.endpoints.web.exposure.include=health,info,metrics
Example
Expose health and metrics endpoints only to authorized monitoring systems.
Code example
management:
endpoints:
web:
exposure:
include: health,info
Diagram
application -> Actuator endpoints -> monitoring system
Key Points
- Do not expose sensitive management endpoints publicly without authentication and authorization.
Q123Concurrency
What is a deadlock and how can it be prevented?
What is a deadlock and how can it be prevented?
Answer
A deadlock occurs when threads wait indefinitely for resources held by one another. Prevention techniques include consistent lock ordering, reducing nested locks, and using timeouts where suitable.
Syntax
lock.tryLock(timeout, unit)
Example
Use an atomic counter or a lock when multiple threads update shared state.
Code example
if (first.tryLock()) { try { if (second.tryLock()) { try { work(); } finally { second.unlock(); } } } finally { first.unlock(); } }
Diagram
thread A holds lock 1 -> waits lock 2
thread B holds lock 2 -> waits lock 1
Key Points
- Collect thread dumps during incidents
- use a consistent global order when multiple locks are required.
Q125Hibernate & JPA
What is the difference between flush and commit?
What is the difference between flush and commit?
Answer
Flush synchronizes pending persistence-context changes with the database, while commit completes the transaction. A flush does not itself guarantee the transaction will commit.
Syntax
entityManager.flush();
Example
Inspect SQL and transaction boundaries when tuning persistence behavior.
Code example
entityManager.persist(entity);
entityManager.flush(); // SQL synchronization, not transaction commit
Diagram
persistence context -> flush SQL -> transaction commit/rollback
Key Points
- Constraints may fail at flush time
- the transaction can still roll back afterward.