Top 40 Hibernate Interview Questions | Must-Prepare before interview.
Top 40 Hibernate Interview Questions | Must-Prepare before interview Work through these 40 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.
Why are index keys dangerous in a sortable or filterable list?
If I sort a todo list keyed by index, the checked box stays on row 0 even though a different todo moved there. I key by todo.id. Index keys are OK only for static lists that...
Why does Context re-render every consumer, and how do you keep RBAC/theme from stalling the tree?
AuthProvider holds user with useMemo. Permission checks go through can(permission) from a hook that reads a stable access object. Theme is a separate provider. High-frequency...
Which JDK 27 APIs still need --enable-preview, and how do LazyConstant and compact headers differ as upgrade stories?
I upgrade the image for G1, headers, and TLS. Preview stays off unless a spike uses LazyConstant or STS and every plugin/container flag matches. If async-profiler or APM...
How does Spring Boot auto-configuration work?
@SpringBootApplication enables @EnableAutoConfiguration, which loads candidate configs from starters. Each auto-config uses @ConditionalOn* to register beans only when...
Describe the Spring Bean lifecycle.
Container instantiates the bean, injects dependencies, runs BeanPostProcessors, then @PostConstruct or InitializingBean. Singleton lives for context lifetime; prototype creates...
What is dependency injection and why does Spring use it?
DI supplies collaborators from outside the class — typically via constructor. Problem solved: tight coupling to concrete classes, hard unit tests, scattered object...
@RestController vs @Controller?
@Controller is for traditional MVC — return "user/list" view name. @RestController adds @ResponseBody so return types become JSON/XML body — standard for REST APIs. Use...
Explain JWT authentication flow in Spring Security.
POST /login with credentials → auth provider validates → issue JWT with exp/sub/roles. Subsequent requests include Bearer token. JwtAuthenticationFilter runs before...
What is CSRF and how does Spring Security handle it?
CSRF tricks logged-in user's browser to POST to your site. Spring stores CsrfToken and validates on mutating requests. For SPA with session cookies, expose token via...
Bean scopes in Spring — singleton vs prototype?
Default singleton shares one instance — stateless services. Prototype for per-operation objects. Request/session scopes tie to web lifecycle with proxies. Prototype inside...
How do you version REST APIs?
We use /api/v1/users for clarity. Non-breaking: add optional JSON fields. Breaking: launch v2 path, maintain v1 for 6 months with Deprecation header. Spring maps...
How does spring.config.import work for externalized configuration?
In K8s: spring.config.import=optional:configtree:/etc/secrets/,optional:configtree:/etc/config/ mounts volumes as properties. Vault:...
How do Spring Boot Actuator health probes work with Kubernetes?
Enable probes, configure K8s readinessProbe on /actuator/health/readiness, liveness on /actuator/health/liveness. Custom HealthIndicator for critical deps on readiness group...
What is the N+1 query problem and how do you fix it?
Loading 100 orders then accessing each order's items triggers 101 queries. Fix with JOIN FETCH in JPQL, @EntityGraph on repository method, or a DTO query selecting only...
How does @Transactional work?
Spring creates a proxy around @Transactional beans. Calling createOrder() from another bean starts a transaction on the thread-bound EntityManager; commit on success, rollback...
What are Spring Boot starters?
spring-boot-starter-web brings spring-webmvc, Tomcat, Jackson with tested versions and enables WebMvcAutoConfiguration. You declare one starter instead of 10 coordinates....
How do you handle exceptions globally in Spring?
Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...
Difference between @Component, @Service, @Repository?
All register as singleton beans via component scan. Choose by layer for readability: @Repository on DAOs (plus SQLException translation), @Service on business logic, @Component...
What is the difference between JPA and Hibernate?
JPA is the API contract; Hibernate is the engine under Spring Boot by default. You write @Entity per JPA spec; Hibernate handles SQL generation. Spring Data JpaRepository adds...
How do you test Spring Boot applications?
Unit test services with Mockito — no Spring. @WebMvcTest + MockMvc for controller contract. @DataJpaTest for repository queries. @SpringBootTest + Testcontainers for critical...
IdentityHashMap vs HashMap — when would you use IdentityHashMap?
Use when identity matters not value — tracking object visitation in deep graph walk. Business keys (userId, email) belong in HashMap with proper equals/hashCode....
What changed migrating Spring Boot 2 to Spring Boot 3 (Jakarta EE)?
Upgrade to Java 17+, replace imports javax.persistence → jakarta.persistence, update Spring Security config to SecurityFilterChain lambda DSL, run OpenRewrite migration recipe,...
When should you use spring.main.lazy-initialization?
Use in test slices or large batch apps where most beans unused per run. Production APIs: fix slow @PostConstruct and DB migrations instead. Combine with...
What does @Lazy mean on injection and on @Configuration?
ServiceA needs ServiceB and vice versa — @Lazy on one injection breaks cycle via proxy. Heavy ReportGenerator @Lazy on admin-only path. Prefer refactoring to remove cycles....
Lazy vs eager fetching in JPA — trade-offs?
Default associations LAZY. Service method needing orders+items uses JOIN FETCH in repository query. Disable spring.jpa.open-in-view=false — forces explicit fetch in service...
When use @Query native SQL vs JPQL in Spring Data JPA?
JPQL for standard entity fetches and portable logic. Native for PostgreSQL-specific jsonb queries, recursive CTEs, or performance-tuned index hints after EXPLAIN. Interface...
How do JPA Specifications (Criteria API) help dynamic queries?
UserSearchSpec.withStatus(status).and(withNameLike(name)) — repository.findAll(spec, pageable). Criteria API verbose — wrap in static factory methods. Alternative: Querydsl or...
What is JPA auditing with @CreatedDate and @LastModifiedDate?
@EnableJpaAuditing + AuditorAware<String> from SecurityContextHolder. Entity: @CreatedDate Instant createdAt; @LastModifiedDate Instant updatedAt. Works with auditing on save()...
How do Flyway/Liquibase integrate with Spring Boot JPA?
Prod: spring.jpa.hibernate.ddl-auto=validate, Flyway V1__init.sql through Vn. CI: @Testcontainers PostgreSQL + Flyway migrate + integration tests. Never rename column without...
Best practices for Spring Data pagination with Pageable?
Controller: @PageableDefault(size=20, sort="createdAt", direction=DESC) Pageable p. Cap size at 100. Admin reports: keyset pagination on id > lastId for deep pages — OFFSET...
What is Hibernate second-level cache and when enable it?
Enable for ProductCategory, Currency — READ_ONLY, rarely changed. spring.jpa.properties.hibernate.cache.use_second_level_cache=true with Caffeine region factory. Avoid on...
How implement multi-tenancy in Spring Security context?
JWT includes tenant_id — converter sets TenantContextHolder. Base entity @Column tenantId validated on save. Repository methods always include tenant predicate — or Hibernate...
What do Java Records provide and their limitations?
DTO: record UserResponse(String id, String name) {} — JSON mapping works. Service layer immutable value objects. Not for entities needing setters/lazy proxies yet. Combine with...
Optional.orElseGet vs orElse — why it matters?
Wrong: cache.orElse(loadFromDb(key)). Right: cache.orElseGet(() -> loadFromDb(key)). Constant default: orElse(Collections.emptyList()). Chain map/flatMap before orElseGet for...
A REST API is slow only in production, not locally. How do you debug it?
Enable Micrometer timers and Hibernate statistics or datasource-proxy in staging with prod-like data. Check Hikari `connections-active`, JVM GC pauses, and Feign/RestClient...
A database connection pool is getting exhausted. How do you identify and solve it?
Enable `spring.datasource.hikari.leak-detection-threshold`. Watch `hikaricp.connections.active` and threads blocked waiting. Fix leaks with try-with-resources; avoid long...
What happens if @Transactional fails midway? How do you verify rollback?
Default: runtime exception marks rollback-only; transaction commits nothing on exit. ```java @Transactional(rollbackFor = Exception.class) public void placeOrder(Order o) {...
How do you reduce startup time of a Spring Boot application?
Exclude unused auto-config, defer heavy beans, use `spring.main.lazy-initialization=true` cautiously in dev. Measure with Spring Boot startup actuator. ```java...
How do you manage schema changes without breaking production?
Add nullable column first; deploy code reading/writing both; backfill; then remove old in later release. ```sql -- V12__add_phone.sql ALTER TABLE users ADD COLUMN phone...
Database is healthy but app shows connection timeout. Why?
DB healthy from admin console but app waits for free connection. Check Hikari pending threads. ```yaml spring.datasource.hikari.maximum-pool-size: 10...
Hibernate Interview Questions and Answers · Top 50 Hibernate Interview Questions and Answers (2026 Edition) · Hibernate Interview Questions Every Fresher Must Know · Hibernate Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform