Prev Next

Hibernate / Hibernate 7 Basics Interview Questions

1. What is Hibernate 7 and when was it released? 2. What is ORM and why is Hibernate used instead of writing raw JDBC? 3. How do you configure Hibernate 7 with Maven? 4. What is an entity in Hibernate 7 and how do you define one? 5. What are entity states in Hibernate 7 and how do they transition? 6. What is the biggest breaking change in Hibernate 7: detached entity reassociation removal? 7. What is the Session in Hibernate 7 and what are its core CRUD operations? 8. What is the Hibernate SessionFactory and how do you create one? 9. What is HQL (Hibernate Query Language) in Hibernate 7? 10. What is JPQL vs HQL in Hibernate 7? 11. How does Hibernate 7 handle primary key generation strategies? 12. What is the first-level cache (persistence context) in Hibernate 7? 13. What is the second-level cache in Hibernate 7 and how does it work with StatelessSession? 14. What are lazy and eager fetching in Hibernate 7 and how do you avoid the N+1 problem? 15. How do you map one-to-many and many-to-one relationships in Hibernate 7? 16. What is the StatelessSession in Hibernate 7 and when should you use it? 17. What is the Criteria API in Hibernate 7 and what are SelectionSpecification and RestrictionSpecification? 18. How does @Embeddable and @Embedded mapping work in Hibernate 7? 19. What are the new FindOptions in Jakarta Persistence 3.2 and Hibernate 7? 20. What is optimistic locking in Hibernate 7 and how do you implement it? 21. What is pessimistic locking in Hibernate 7 and what are the improvements? 22. What is the @ManyToMany relationship in Hibernate 7 and how do you map it? 23. What is Hibernate's flush behaviour and how does it affect SQL execution? 24. What are named queries in Hibernate 7 and how are they type-safe with TypedQueryReference? 25. What is the @Inheritance mapping in Hibernate 7 and what strategies are available? 26. What is the @Filter and auto-enabled filters feature in Hibernate 7? 27. What is key-based pagination in Hibernate 7 and how does it differ from offset pagination? 28. What is Jakarta Data 1.0 and how does it integrate with Hibernate 7? 29. What is the @NaturalId feature in Hibernate 7 and what is @NaturalIdClass? 30. How does Hibernate 7 support vector data types for AI/ML applications? 31. What are the key removed APIs in Hibernate 7 and how do you migrate? 32. What is @SQLRestriction and @SQLJoinTableRestriction in Hibernate 7? 33. How does Hibernate 7 handle schema validation and generation (hbm2ddl)? 34. What are Hibernate 7's improvements to multi-tenancy support? 35. What is the @Check constraint and @ColumnDefault annotation in Hibernate 7? 36. What is @BatchSize and how does it solve the N+1 problem differently from JOIN FETCH? 37. What is Hibernate 7's @Struct mapping for database composite types? 38. What are Hibernate 7's logging improvements for SQL and parameter binding? 39. How does Hibernate 7 work with Spring Boot 4 - what is auto-configured? 40. What are the key Hibernate 7 vs Hibernate 6 differences interviewers ask about?

1. What is Hibernate 7 and when was it released?

Hibernate ORM 7 is the current major version of Hibernate, the most widely used Java ORM framework. Hibernate 7.0 was released on May 20, 2025 . The current latest stable release is 7.4 (mid-2026). First production-ready release entirely under Apache Software License v2 (including Envers) Complet...

Read full answer

2. What is ORM and why is Hibernate used instead of writing raw JDBC?

ORM (Object-Relational Mapping) automatically maps Java objects to relational database tables, eliminating JDBC boilerplate. Hibernate is the most widely used Java ORM. Raw JDBC vs Hibernate Task Raw JDBC Hibernate Query Write SQL, iterate ResultSet, map columns session.find(Order.class, id) or J...

Read full answer

3. How do you configure Hibernate 7 with Maven?

Hibernate 7 can be used standalone or as the JPA provider in Spring Boot 4. Key dependencies: org.hibernate.orm hibernate-core 7.4.0.Final <...

Read full answer

4. What is an entity in Hibernate 7 and how do you define one?

An entity is a Java class mapped to a database table. Each instance corresponds to a row. In Hibernate 7, entity classes follow Jakarta Persistence 3.2 rules. import jakarta.persistence. * ; @Entity @Table (name = "products" ) public class Product { @Id @GeneratedValue (strategy = GenerationType ...

Read full answer

5. What are entity states in Hibernate 7 and how do they transition?

Every entity instance in Hibernate exists in one of three states relative to a Session. Hibernate 7 enforces stricter rules on detached entities. The three entity states State Description In session? DB record? Transient Never associated with a Session No No Persistent Associated with open Sessio...

Read full answer

6. What is the biggest breaking change in Hibernate 7: detached entity reassociation removal?

The most impactful breaking change in Hibernate 7 is the complete removal of detached entity reassociation . Methods like session.update() , session.saveOrUpdate() , and session.lock() on detached entities are removed. Removed reassociation operations Removed method Replacement session.update(ent...

Read full answer

7. What is the Session in Hibernate 7 and what are its core CRUD operations?

The Session is Hibernate's primary interface for database operations. It represents a unit of work and maintains the first-level cache. Key API changes in Hibernate 7: Session method changes Old method (removed) Hibernate 7 replacement session.save(entity) session.persist(entity) session.get(Clas...

Read full answer

8. What is the Hibernate SessionFactory and how do you create one?

The SessionFactory is the central, thread-safe, immutable configuration object. It is expensive to create and should be instantiated once per application lifecycle. Configuration config = new Configuration(); config.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/mydb");...

Read full answer

9. What is HQL (Hibernate Query Language) in Hibernate 7?

HQL is Hibernate's object-oriented query language operating on entity objects rather than tables. Hibernate 7 adds new HQL functions including regexp, JSON/XML manipulation, and set-returning functions. // Basic HQL - uses entity class name , not table name: List < Product > all = session . creat...

Read full answer

10. What is JPQL vs HQL in Hibernate 7?

JPQL is the standardised query language from Jakarta Persistence. HQL is a strict superset with additional Hibernate-specific features. JPQL vs HQL Aspect JPQL HQL Specification Jakarta Persistence 3.2 standard Hibernate superset of JPQL Portability Works with any JPA provider Hibernate-specific ...

Read full answer

11. How does Hibernate 7 handle primary key generation strategies?

Primary key generation is controlled by @GeneratedValue . Hibernate 7 supports all four JPA strategies plus UUID as a first-class feature. @GeneratedValue strategies Strategy How it works Best for IDENTITY DB auto-increment (SERIAL/AUTO_INCREMENT) Simple setups; disables JDBC batch inserts SEQUEN...

Read full answer

12. What is the first-level cache (persistence context) in Hibernate 7?

The first-level cache is the per-Session in-memory cache for all entities loaded or persisted within an open Session. It is mandatory - every Session has its own first-level cache. Session session = sf.openSession(); session.beginTransaction(); Product p1 = session.find(Product.class, 1L); // DB ...

Read full answer

13. What is the second-level cache in Hibernate 7 and how does it work with StatelessSession?

The second-level cache is an optional cross-session application-wide cache. Hibernate 7 changes StatelessSession's behaviour: it now reads/writes the L2 cache by default (was bypassed in v6). Cache level comparison Aspect First-level cache Second-level cache Scope Per Session Per SessionFactory (...

Read full answer

14. What are lazy and eager fetching in Hibernate 7 and how do you avoid the N+1 problem?

Lazy fetching loads associations on demand. Eager fetching loads them immediately. Wrong strategy choice leads to the N+1 query problem. // LAZY (default for @OneToMany ): @OneToMany (mappedBy = "customer" , fetch = FetchType . LAZY) private List < Order > orders; // N + 1 PROBLEM: // 1 query: SE...

Read full answer

15. How do you map one-to-many and many-to-one relationships in Hibernate 7?

Relationships are mapped using @OneToMany , @ManyToOne , etc. The owning side holds the foreign key column. @Entity public class Customer { @Id @GeneratedValue (strategy = GenerationType . IDENTITY) private Long id; private String name; @OneToMany ( mappedBy = "customer" , cascade = CascadeType ....

Read full answer

16. What is the StatelessSession in Hibernate 7 and when should you use it?

StatelessSession has no first-level cache, no dirty checking, and no automatic state management. In Hibernate 7 it reaches near feature-parity with Session and is the preferred tool for bulk processing. Session vs StatelessSession Aspect Session StatelessSession First-level cache Yes No Dirty che...

Read full answer

17. What is the Criteria API in Hibernate 7 and what are SelectionSpecification and RestrictionSpecification?

Hibernate 7 introduces a new type-safe Criteria-like API: SelectionSpecification and RestrictionSpecification - simpler than the JPA Criteria API for common cases while remaining fully type-safe via the static metamodel. // Static metamodel auto - generated by hibernate - processor: // public abs...

Read full answer

18. How does @Embeddable and @Embedded mapping work in Hibernate 7?

@Embeddable marks a class as a value type stored within the parent entity's table. Hibernate 7 adds @EmbeddedColumnNaming (incubating) to simplify prefix/suffix mapping for multiple embeddables of the same type. @Embeddable public class Address { @Column (name = "street" ) private String street; ...

Read full answer

19. What are the new FindOptions in Jakarta Persistence 3.2 and Hibernate 7?

Jakarta Persistence 3.2 introduces FindOption , RefreshOption , and LockOption for fine-grained control over find/refresh/lock operations without separate methods for each combination. Hibernate 7 also adds session.findMultiple() . // Before JP 3.2 : separate methods for different behaviours // A...

Read full answer

20. What is optimistic locking in Hibernate 7 and how do you implement it?

Optimistic locking uses a version column to detect concurrent update conflicts at commit time instead of locking the row. Hibernate 7 throws OptimisticLockException when the version has changed since the entity was loaded. @Entity public class Product { @Id @GeneratedValue (strategy = GenerationT...

Read full answer

21. What is pessimistic locking in Hibernate 7 and what are the improvements?

Pessimistic locking acquires a DB-level lock on a row when loaded. Hibernate 7 improves this with the Timeouts API from Jakarta Persistence 3.2. // PESSIMISTIC_WRITE: SELECT ... FOR UPDATE Product p = session . find(Product . class, id, LockModeType . PESSIMISTIC_WRITE); // Hibernate 7 : Timeouts...

Read full answer

22. What is the @ManyToMany relationship in Hibernate 7 and how do you map it?

A many-to-many relationship requires a join table. Each entity can be associated with multiple instances of the other. @Entity public class Student { @Id @GeneratedValue (strategy = GenerationType . IDENTITY) private Long id; private String name; @ManyToMany (fetch = FetchType . LAZY) @JoinTable ...

Read full answer

23. What is Hibernate's flush behaviour and how does it affect SQL execution?

Flushing synchronises the in-memory persistence context with the database by sending pending SQL. Flush does NOT commit the transaction. Hibernate flush modes FlushMode When SQL sent Use case AUTO (default) Before queries and at commit Normal transactional operations COMMIT Only at commit Read-he...

Read full answer

24. What are named queries in Hibernate 7 and how are they type-safe with TypedQueryReference?

Named queries are pre-defined HQL/SQL queries. Hibernate 7 (Jakarta Persistence 3.2) adds TypedQueryReference for type-safe, compile-time references via the static metamodel. @Entity @NamedQuery ( name = "Product.findByCategory" , query = "FROM Product p WHERE p.category = :category ORDER BY p.pr...

Read full answer

25. What is the @Inheritance mapping in Hibernate 7 and what strategies are available?

Three strategies map a Java inheritance hierarchy to database tables, each with different performance and schema trade-offs. Inheritance strategies Strategy Schema Pros Cons SINGLE_TABLE One table for all subclasses Simple; best query performance Sparse NULLs; no NOT NULL on subtype columns JOINE...

Read full answer

26. What is the @Filter and auto-enabled filters feature in Hibernate 7?

Hibernate Filters are parameterised WHERE clause fragments applied to a Session. Hibernate 7 adds auto-enabled filters that activate automatically without explicit session.enableFilter() calls. @FilterDef ( name = "activeFilter" , parameters = @ParamDef (name = "isActive" , type = Boolean . class...

Read full answer

27. What is key-based pagination in Hibernate 7 and how does it differ from offset pagination?

Traditional offset pagination ( LIMIT N OFFSET M ) gets slower on deep pages. Key-based pagination uses a WHERE clause on the last key value, making each page O(1) regardless of depth. // OFFSET PAGINATION (gets slower at depth): List < Product > page1000 = session . createQuery( "FROM Product OR...

Read full answer

28. What is Jakarta Data 1.0 and how does it integrate with Hibernate 7?

Jakarta Data 1.0 is a new specification in Jakarta EE 11 providing a standardised type-safe repository model. Hibernate 7 provides a complete implementation via hibernate-repositories module. import jakarta.data.repository. * ; @Repository public interface ProductRepository extends CrudRepository...

Read full answer

29. What is the @NaturalId feature in Hibernate 7 and what is @NaturalIdClass?

A natural ID is a business-meaningful unique identifier distinct from the surrogate PK. Hibernate 7 adds @NaturalIdClass for composite natural IDs. @Entity public class Book { @Id @GeneratedValue (strategy = GenerationType . IDENTITY) private Long id; // surrogate PK (internal) @NaturalId // busi...

Read full answer

30. How does Hibernate 7 support vector data types for AI/ML applications?

Hibernate 7 (especially 7.2+) adds native support for vector data types used in AI embeddings, enabling semantic search alongside relational data. import org.hibernate.annotations.Array ; import org.hibernate.type.SqlTypes ; @Entity public class Document { @Id @GeneratedValue private Long id; pri...

Read full answer

31. What are the key removed APIs in Hibernate 7 and how do you migrate?

Hibernate 7 removes all APIs deprecated in Hibernate 6.x. Anything deprecated in 6.x is hard-deleted in 7.0 with no fallback. Key API removals in Hibernate 7 Removed Replacement session.save() session.persist() session.get() session.find() session.delete() session.remove() session.update() sessio...

Read full answer

32. What is @SQLRestriction and @SQLJoinTableRestriction in Hibernate 7?

Hibernate 7 adds @SQLRestriction (replacing removed @Where ) to apply a permanent SQL WHERE clause to an entity or collection mapping. import org.hibernate.annotations.SQLRestriction ; // Soft - delete: only ever load non - deleted records @Entity @SQLRestriction ( "deleted_at IS NULL" ) // appli...

Read full answer

33. How does Hibernate 7 handle schema validation and generation (hbm2ddl)?

Hibernate can validate or generate the DB schema from entity mappings. Controlled by hibernate.hbm2ddl.auto . hbm2ddl.auto values Value Behaviour Use in none No schema action Production (use Flyway/Liquibase) validate Validates entity mappings match schema; fails on mismatch Production safety che...

Read full answer

34. What are Hibernate 7's improvements to multi-tenancy support?

Hibernate 7 enhances multi-tenancy with better integration with auto-enabled filters for discriminator-based tenancy. Multi-tenancy strategies Strategy Isolation Use case DATABASE Highest - one DB per tenant Regulated industries; highest cost SCHEMA High - one schema per tenant Good balance; Post...

Read full answer

35. What is the @Check constraint and @ColumnDefault annotation in Hibernate 7?

Hibernate 7 provides DDL-level annotations for database constraints and default values applied during schema generation. @Entity @Check (name = "price_positive" , constraints = "price > 0" ) // table - level check public class Product { @Id @GeneratedValue (strategy = GenerationType . IDENTITY) p...

Read full answer

36. What is @BatchSize and how does it solve the N+1 problem differently from JOIN FETCH?

@BatchSize loads lazy-loaded collections or proxies in batches using IN clauses rather than one-by-one. Unlike JOIN FETCH it works correctly with pagination. @Entity public class Customer { @Id private Long id; private String name; @OneToMany (mappedBy = "customer" , fetch = FetchType . LAZY) @Ba...

Read full answer

37. What is Hibernate 7's @Struct mapping for database composite types?

Hibernate 7 adds @Struct for mapping Java records to database composite/structured types (native types in PostgreSQL, Oracle, DB2) stored as a single column value. import org.hibernate.annotations.Struct ; @Embeddable @Struct (name = "address_type" ) // maps to the DB composite type public record...

Read full answer

38. What are Hibernate 7's logging improvements for SQL and parameter binding?

Hibernate 7 replaces the deprecated use_sql_comments property with a cleaner logging hierarchy. SQL parameter binding logging is now available natively without a JDBC proxy driver. # Hibernate 7 logging configuration: logging: level: # SQL statement logging: org.hibernate.SQL: DEBUG # shows the S...

Read full answer

39. How does Hibernate 7 work with Spring Boot 4 - what is auto-configured?

In Spring Boot 4, Hibernate 7 is the default JPA provider auto-configured transparently when spring-boot-starter-data-jpa is on the classpath. # Complete...

Read full answer

40. What are the key Hibernate 7 vs Hibernate 6 differences interviewers ask about?

The most common comparison question in enterprise Java interviews. Here is a structured summary of all major changes. Hibernate 6 vs Hibernate 7 Dimension Hibernate 6 Hibernate 7 GA release June 2022 May 20, 2025 Jakarta Persistence 3.1 3.2 (complete) Jakarta Data Not supported 1.0 (complete) Lic...

Read full answer

«
»

Comments & Discussions