Hibernate / JPA Interview Questions Hindi mein

Hibernate / JPA कोर्स के 25 सवाल, हर सवाल के सही जवाब और explanation के साथ। जवाब देखने से पहले ख़ुद सोचें।

ORM, JPA and Hibernate

1. What is the relationship between JPA and Hibernate?

  1. JPA is the specification; Hibernate is an implementation of it
  2. They are competing databases
  3. Hibernate is the specification; JPA implements it
  4. JPA is a Spring module
जवाब देखें

जवाब: JPA is the specification; Hibernate is an implementation of it

Jakarta Persistence defines the API; Hibernate ORM implements it and adds extra features.

पाठ: Why ORM, and What JPA and Hibernate Are

2. What is a safe setting for spring.jpa.hibernate.ddl-auto in production?

  1. create-drop
  2. update
  3. create
  4. validate (with Flyway or Liquibase managing the schema)
जवाब देखें

जवाब: validate (with Flyway or Liquibase managing the schema)

validate checks the mapping without changing the schema; migrations are handled by a dedicated tool.

पाठ: Setting Up JPA with Spring Boot

3. Which is required for a JPA entity class?

  1. A public all-arguments constructor only
  2. Every field marked @Column
  3. An @Id field and a no-argument constructor (which may be protected)
  4. The class must be a record
जवाब देखें

जवाब: An @Id field and a no-argument constructor (which may be protected)

Entities need a primary key and a no-arg constructor that the provider can call.

पाठ: Your First Entity

The Persistence Context

4. What does `em.merge(detachedProduct)` return?

  1. Nothing; it updates the argument in place
  2. A new transient object
  3. A managed instance with the detached object's state copied onto it
  4. The database row count
जवाब देखें

जवाब: A managed instance with the detached object's state copied onto it

merge returns the managed copy; the argument itself remains detached.

पाठ: EntityManager Operations

5. Inside a transaction, you load an entity and change one field without calling save. What happens at commit?

  1. Nothing; changes are lost
  2. Hibernate detects the change by dirty checking and issues an UPDATE
  3. An exception is thrown
  4. The entity is deleted
जवाब देखें

जवाब: Hibernate detects the change by dirty checking and issues an UPDATE

Managed entities are compared with their snapshot at flush, and changes are written automatically.

पाठ: Entity States and Dirty Checking

6. With the default flush mode, when does Hibernate flush pending changes?

  1. Before commit and before queries that may be affected by the pending changes
  2. Only when the application shuts down
  3. After every setter call
  4. Never, unless flush() is called
जवाब देखें

जवाब: Before commit and before queries that may be affected by the pending changes

FlushModeType.AUTO flushes before commit and before relevant queries.

पाठ: Flushing, the First-Level Cache and Transactions

Mapping Types, Keys and Inheritance

7. Why is @Enumerated(EnumType.STRING) preferred over the default ORDINAL?

  1. Ordinals change meaning when enum constants are reordered or inserted, corrupting existing data
  2. Strings are faster to compare
  3. ORDINAL is not supported by Hibernate
  4. STRING uses less storage
जवाब देखें

जवाब: Ordinals change meaning when enum constants are reordered or inserted, corrupting existing data

Stored ordinals depend on declaration order, which changes as the code evolves.

पाठ: Basic Types, Enums, Embeddables and Converters

8. Why can IDENTITY ID generation prevent Hibernate from batching inserts?

  1. IDENTITY IDs are random
  2. IDENTITY is not supported by JDBC
  3. Batching requires UUIDs
  4. The ID is only known after each INSERT executes, so Hibernate must insert immediately on persist
जवाब देखें

जवाब: The ID is only known after each INSERT executes, so Hibernate must insert immediately on persist

Hibernate needs the generated key right away, forcing one INSERT per persist.

पाठ: Primary Keys and ID Generation

9. Which inheritance strategy stores all subclasses in one table with a discriminator column?

  1. JOINED
  2. TABLE_PER_CLASS
  3. SINGLE_TABLE
  4. @MappedSuperclass
जवाब देखें

जवाब: SINGLE_TABLE

SINGLE_TABLE uses one table plus a discriminator to tell rows apart.

पाठ: Inheritance Mapping Strategies

Relationships

10. In a bidirectional one-to-many mapping, which side writes the foreign key?

  1. The @OneToMany side with mappedBy
  2. Both sides equally
  3. The @ManyToOne side (the owning side)
  4. Neither; the database decides
जवाब देखें

जवाब: The @ManyToOne side (the owning side)

The owning side, the @ManyToOne field, determines the foreign key value.

पाठ: @ManyToOne, @OneToMany and the Owning Side

11. A student-course relationship needs to store the grade. How should it be mapped?

  1. @ManyToMany with a List
  2. An explicit association entity (e.g. Enrolment) with two @ManyToOne relationships
  3. A comma-separated column
  4. @OneToOne
जवाब देखें

जवाब: An explicit association entity (e.g. Enrolment) with two @ManyToOne relationships

Attributes on the link require an entity for the association.

पाठ: Many-to-Many and One-to-One

12. Where is CascadeType.ALL with orphanRemoval appropriate?

  1. From an order to its order lines, which belong only to that order
  2. From an order to its customer
  3. From any entity to every related entity
  4. On every @ManyToMany
जवाब देखें

जवाब: From an order to its order lines, which belong only to that order

Cascade and orphan removal suit owned children in a composition, not independent entities.

पाठ: Cascades, Orphan Removal and Entity Equality

Fetching and Performance

13. What is the default fetch type of @ManyToOne in JPA?

  1. EAGER
  2. LAZY
  3. NONE
  4. It depends on the database
जवाब देखें

जवाब: EAGER

@ManyToOne and @OneToOne default to EAGER; best practice is to set them to LAZY explicitly.

पाठ: Lazy and Eager Loading

14. You load 200 orders and print each order's customer name, and the SQL log shows 201 queries. What is the most direct fix?

  1. Switch every association to EAGER
  2. Increase the connection pool size
  3. Disable SQL logging
  4. Use join fetch (or an entity graph) for the customer association in that query
जवाब देखें

जवाब: Use join fetch (or an entity graph) for the customer association in that query

Fetching the association in the same query removes the per-row queries.

पाठ: The N+1 Select Problem

15. Why are DTO projections often better than entities for read-only list screens?

  1. They are required by JPA
  2. They automatically cache results forever
  3. They select only needed columns and avoid persistence-context tracking and lazy-loading issues
  4. They can update the database directly
जवाब देखें

जवाब: They select only needed columns and avoid persistence-context tracking and lazy-loading issues

Projections fetch exactly what the screen needs without entity management overhead.

पाठ: DTO Projections and Read Models

Querying

16. How should user input be included in a JPQL query?

  1. By concatenating strings
  2. By escaping quotes manually
  3. Through named or positional parameters
  4. Via system properties
जवाब देखें

जवाब: Through named or positional parameters

Parameters prevent injection and let the database reuse statement plans.

पाठ: JPQL Essentials

17. When are the Criteria API or Spring Data Specifications most useful?

  1. For queries whose shape never changes
  2. For dynamic queries where filters are optional and combined at run time
  3. For database migrations
  4. For configuring connection pools
जवाब देखें

जवाब: For dynamic queries where filters are optional and combined at run time

They build query predicates programmatically, avoiding string concatenation for dynamic filters.

पाठ: Criteria API and Specifications

18. What is a risk of running a JPQL bulk update in the same persistence context as loaded entities?

  1. Loaded entities keep stale values because bulk operations bypass the persistence context
  2. The update is ignored
  3. It always deadlocks
  4. It disables transactions
जवाब देखें

जवाब: Loaded entities keep stale values because bulk operations bypass the persistence context

Bulk statements go straight to the database; clear the context or use a separate transaction.

पाठ: Native SQL and Bulk Operations

Transactions, Locking and Caching

19. A checked exception escapes a Spring @Transactional method without rollbackFor. What happens by default?

  1. The transaction is committed
  2. The transaction is rolled back
  3. Spring retries the method
  4. The application stops
जवाब देखें

जवाब: The transaction is committed

By default only unchecked exceptions and errors trigger rollback.

पाठ: Transactions with Spring and JPA

20. What does a @Version attribute enable?

  1. Automatic database backups
  2. Faster inserts
  3. Second-level caching
  4. Optimistic locking that detects concurrent modifications and prevents lost updates
जवाब देखें

जवाब: Optimistic locking that detects concurrent modifications and prevents lost updates

Version checks in UPDATE statements detect conflicting concurrent changes.

पाठ: Optimistic and Pessimistic Locking

21. Which data is the best candidate for Hibernate's second-level cache?

  1. Order lines that change every second
  2. Data updated by external batch jobs directly in SQL
  3. Read-mostly reference data such as countries and categories
  4. Every entity by default
जवाब देखें

जवाब: Read-mostly reference data such as countries and categories

L2 caching pays off for rarely changing data that is read often by ID.

पाठ: Second-Level and Query Caching

Spring Data JPA, Performance, Testing and Revision

22. What does a Spring Data method named findByStatusAndPlacedAtAfter(status, date) do?

  1. It must be implemented manually
  2. It loads every row and filters in Java
  3. Spring Data derives a query filtering by status and placedAt greater than the given date
  4. It creates a database index
जवाब देखें

जवाब: Spring Data derives a query filtering by status and placedAt greater than the given date

Derived query methods are parsed from their names into JPQL.

पाठ: Spring Data JPA Repositories

23. Which setting allows Hibernate to send many INSERT statements in one JDBC batch?

  1. spring.jpa.open-in-view=true
  2. hibernate.jdbc.batch_size (with SEQUENCE IDs)
  3. ddl-auto=update
  4. FetchType.EAGER
जवाब देखें

जवाब: hibernate.jdbc.batch_size (with SEQUENCE IDs)

JDBC batching groups statements; IDENTITY IDs would prevent insert batching.

पाठ: Performance Checklist

24. Why is testing JPA code against a real database (e.g. via Testcontainers) preferred over H2?

  1. Real databases match production dialect, types and constraints, so tests catch issues H2 would miss
  2. H2 is not supported by Spring
  3. Testcontainers is faster than in-memory databases in every case
  4. H2 cannot run JPQL
जवाब देखें

जवाब: Real databases match production dialect, types and constraints, so tests catch issues H2 would miss

Dialect and behaviour differences mean H2 can hide bugs that appear in production.

पाठ: Testing the Persistence Layer

25. Which combination fixes an N+1 problem when listing orders with their customer names?

  1. Make customer EAGER and enable open-in-view
  2. Increase the transaction timeout
  3. Use EnumType.ORDINAL
  4. Use join fetch or an entity graph for customer, or a DTO projection selecting the name
जवाब देखें

जवाब: Use join fetch or an entity graph for customer, or a DTO projection selecting the name

Fetching the association in the same query or projecting the needed column avoids per-row queries.

पाठ: Revision and Interview Questions

← कोर्स पर वापस जाएँ