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
vsEAGER
wisely. Avoid n+1 problems withJOIN 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:
-
Transient: New object, not associated with DB.
-
Persistent: Associated with a Hibernate
Session
. -
Detached: After session is closed, but object still exists.
-
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
orJOIN 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
orMERGE
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
andMultiTenantConnectionProvider
.
๐ 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
orNamedQuery
. -
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