Tuesday, July 22, 2025

JPA / Hibernate – Architect-Level Interview Q&A

 

 1. What is the difference between JPA and Hibernate?

Answer:

  • JPA (Java Persistence API) is a specification.

  • Hibernate is a JPA implementation (and more) that provides additional features like caching, custom queries, and batch processing.

  • JPA defines annotations, EntityManager, and query language (JPQL); Hibernate provides the actual engine and can be used in native (non-JPA) mode.


๐Ÿ— 2. How do you manage entity relationships in a large domain model?

Answer:

  • Use proper annotations: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany.

  • Avoid bidirectional relationships unless necessary to prevent infinite recursion and cyclic dependencies.

  • Use @JsonManagedReference / @JsonBackReference for serialization issues.

  • Prefer LAZY fetching for associations unless eager loading is necessary.


๐Ÿ“Š 3. How do you optimize performance in Hibernate-heavy applications?

Answer:

  • Batching: Use hibernate.jdbc.batch_size to reduce round trips.

  • Fetch Strategy: Use LAZY vs EAGER wisely. Avoid n+1 problems with JOIN FETCH or @EntityGraph.

  • Caching:

    • 1st Level: Built-in per session.

    • 2nd Level: Use EhCache, Redis, or Hazelcast.

    • Query Cache: Enable carefully with selective query regions.

  • Pagination: Always use pagination for large result sets.

  • DTO Projection: Use Constructor expressions, native SQL, or Spring Data projections for read-heavy use cases.


๐Ÿง  4. Explain the Hibernate Session Lifecycle.

Answer:

  1. Transient: New object, not associated with DB.

  2. Persistent: Associated with a Hibernate Session.

  3. Detached: After session is closed, but object still exists.

  4. Removed: Marked for deletion.


⚙️ 5. What is the N+1 problem and how do you fix it?

Answer:
Occurs when a single query loads multiple parent entities, but each associated child is fetched in a separate query.

Fixes:

  • Use @EntityGraph or JOIN FETCH.

  • Batch size configuration: hibernate.default_batch_fetch_size.

  • Use DTO-based projections.


๐Ÿ” 6. How do you handle circular dependencies in bi-directional mappings?

Answer:

  • Mark one side as @JsonManagedReference and the other as @JsonBackReference if using Jackson.

  • Or use @JsonIgnore on one side.

  • Alternatively, use DTOs to break dependency for serialization.


๐Ÿ›‘ 7. What are some pitfalls with Cascade operations?

Answer:

  • Overuse of CascadeType.ALL may lead to unintended deletions.

  • Avoid cascading REMOVE in collections unless strictly needed.

  • Be explicit: prefer PERSIST or MERGE only.


๐Ÿงฉ 8. How do you handle inheritance in JPA?

Answer:

  • SINGLE_TABLE: One table for all types (use discriminator column).

  • JOINED: Parent/child mapped to separate tables with join.

  • TABLE_PER_CLASS: Each subclass gets its own table (less common).

Prefer JOINED for normalized DBs, or SINGLE_TABLE for performance.


๐Ÿ’พ 9. How do you handle multi-tenancy in Hibernate?

Answer:

  • Use Hibernate Multi-Tenant support:

    • Schema-based: One DB, multiple schemas.

    • Database-based: Separate DBs per tenant.

    • Discriminator-based: One table, add tenant_id.

  • Implement a CurrentTenantIdentifierResolver and MultiTenantConnectionProvider.


๐Ÿ›  10. How do you tune Hibernate for large-scale applications?

Answer:

  • Enable second-level cache selectively.

  • Use stateless sessions for bulk inserts.

  • Avoid over-fetching by limiting graph depth.

  • Optimize entity mappings (avoid @ManyToMany where possible).

  • Use connection pooling (HikariCP).

  • Enable slow query logging.


๐Ÿงช 11. How do you structure repositories in a large modular project?

Answer:

  • Use Spring Data JPA interfaces with custom base interfaces (BaseRepository<T, ID>).

  • Implement custom queries with @Query or NamedQuery.

  • Group repositories by domain or bounded context.

  • Avoid business logic in repositories—delegate to service layer.


๐Ÿ” 12. How do you debug performance issues in JPA/Hibernate?

Answer:

  • Enable SQL logging: spring.jpa.show-sql=true, Hibernate format SQL.

  • Use tools: JProfiler, YourKit, or Hibernate Statistics.

  • Track slow queries using logs or DB monitoring.

  • Profile batch size issues or n+1 queries.


๐Ÿ”ง 13. What’s the difference between merge() and saveOrUpdate()?

Answer:

  • saveOrUpdate(): Saves a transient or detached instance.

  • merge(): Returns a new managed copy; original remains detached.

  • Prefer merge() when working with detached entities from outside session context.


๐Ÿ’ฌ 14. How do you enforce audit tracking in entities?

Answer:

  • Use @CreatedDate, @LastModifiedDate with @EnableJpaAuditing.

  • Store created/modified by with Spring Security context.

  • Alternatively, use Hibernate Envers for historical tracking.


๐Ÿ“ฆ 15. Should you map everything as entities?

Answer:
No. Use entities for write-heavy models. Use DTOs, views, or native queries for:

  • Read-heavy or reporting use cases.

  • Aggregated or denormalized data.

  • Reducing entity complexity.

No comments:

Post a Comment