Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsHibernate & Spring Data JPA
✓ FreeBeginner· 8 min read

Hibernate & JPA Core Concepts — Interview Questions

What Hibernate is, JPA vs Hibernate, core components, SessionFactory and Session (EntityManagerFactory/EntityManager), transactions, HQL/JPQL, the Criteria API, entity states, bootstrapping, the second-level cache, get() vs load(), and data integrity.

Published September 25, 2026


How to use this lesson

Answer Hibernate questions in JPA terms first, then add the Hibernate specifics. Modern Spring code uses EntityManager and Spring Data repositories, and Hibernate is the implementation underneath. Knowing both vocabularies (Session ↔ EntityManager) shows you've used it for real.

Q1. What is Hibernate?

Short answer: Hibernate is the most widely used Java ORM (object-relational mapping) framework, and the default JPA implementation in Spring Boot. It maps Java classes to tables, and objects to rows. It generates the SQL for CRUD operations, manages entity state and dirty checking, handles relationships, lazy loading and caching, and translates between Java types and SQL types.

Key points to cover:

  • JPA (Jakarta Persistence) is the specification: annotations, EntityManager, JPQL. Hibernate is an implementation, with extra features (Envers, custom types, second-level cache integrations).
  • ORM removes JDBC boilerplate, but you still need to understand the SQL it generates.

Learn it in depth → N+1 Query Problem

Q2. What are the core components of Hibernate?

Short answer:

  • Configuration/bootstrap: reads the settings and mappings.
  • SessionFactory: a thread-safe, expensive factory, one per database.
  • Session: the unit of work, holding the persistence context.
  • Transaction.
  • Query (HQL, native SQL, Criteria).
  • A connection provider, typically a pool such as HikariCP.
  • Optional caches: first-level (per session) and second-level (shared).

JPA equivalents: EntityManagerFactory, EntityManager, EntityTransaction, TypedQuery.

Q3. What is the role of the SessionFactory?

Short answer: It's built once at startup from the configuration and mappings. It holds the compiled metadata, the connection provider and the second-level cache, and it creates Sessions. It's thread-safe and heavyweight, so there's one per database per application. In JPA it's the EntityManagerFactory, which Spring Boot creates for you.

Q4. What is a Session?

Short answer: A short-lived, single-threaded unit of work between the application and the database (JPA: EntityManager). It holds the persistence context, the first-level cache of the entities it has loaded, which tracks their changes. At flush or commit, it writes those changes to the database.

Key points to cover:

  • It isn't thread-safe. Never share a session between threads or requests.
  • In Spring, you inject an EntityManager. It's a proxy bound to the current transaction, so each transaction gets its own persistence context.

Q5. How does Hibernate manage transactions?

Short answer: All writes happen inside a transaction. Plain Hibernate uses session.beginTransaction() and commit()/rollback(), on top of either a JDBC connection's transaction or JTA (for distributed or container-managed transactions). In Spring applications you use @Transactional, and Spring's JpaTransactionManager begins, commits or rolls back the transaction, and binds the EntityManager to it.

@Service
class TransferService {
    @Transactional
    public void transfer(long fromId, long toId, BigDecimal amount) {
        Account from = accounts.findById(fromId).orElseThrow();
        Account to = accounts.findById(toId).orElseThrow();
        from.debit(amount);
        to.credit(amount);
        // no save() needed: dirty checking flushes both UPDATEs at commit; any RuntimeException rolls back both
    }
}

Learn it in depth → @Transactional Deep Dive

Q6. What is HQL?

Short answer: Hibernate Query Language, the superset of JPA's JPQL. It's an object-oriented query language that queries entities and their properties, not tables and columns. It understands associations, inheritance and polymorphism, and Hibernate translates it into the database's SQL dialect.

List<Order> recent = em.createQuery(
        "select o from Order o join fetch o.customer c where c.city = :city and o.createdAt > :since", Order.class)
    .setParameter("city", "Pune")
    .setParameter("since", Instant.now().minus(7, ChronoUnit.DAYS))
    .getResultList();

Key points to cover:

  • In Spring Data JPA, the same queries go into @Query("select o from Order o where …"), or are derived from method names (findByCustomerCityAndCreatedAtAfter).

Q7. What is the Criteria API?

Short answer: A programmatic, type-safe way to build queries in Java code instead of strings. It's ideal for dynamic queries whose filters depend on user input, such as search screens.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> q = cb.createQuery(Product.class);
Root<Product> p = q.from(Product.class);
List<Predicate> filters = new ArrayList<>();
if (name != null)     filters.add(cb.like(cb.lower(p.get("name")), "%" + name.toLowerCase() + "%"));
if (maxPrice != null) filters.add(cb.le(p.get("price"), maxPrice));
q.where(filters.toArray(Predicate[]::new));
List<Product> results = em.createQuery(q).getResultList();

Key points to cover:

  • Hibernate's old proprietary Criteria API was deprecated, and removed in Hibernate 6. Use the JPA Criteria API, or Spring Data Specifications, which wrap it neatly. Querydsl and jOOQ are popular alternatives.

Q8. What are the entity (object) states in Hibernate?

Short answer:

  • Transient: new, not associated with a session, no database row.
  • Persistent (managed): attached to an open persistence context. Changes are tracked and flushed automatically.
  • Detached: was managed, but the session is closed. Changes are no longer tracked.
  • Removed: scheduled for deletion.
Customer c = new Customer("Asha");      // transient
em.persist(c);                          // managed: INSERT at flush
c.setCity("Pune");                      // tracked: UPDATE at flush (dirty checking)
em.detach(c);                           // detached: further changes are ignored…
Customer merged = em.merge(c);          // …until merged back (merge returns the managed copy)
em.remove(merged);                      // removed: DELETE at flush

Q9. What is the purpose of the Configuration class?

Short answer: In native Hibernate, Configuration (or the newer StandardServiceRegistryBuilder + MetadataSources) bootstraps Hibernate. It loads settings (from hibernate.cfg.xml or properties), registers the mapped classes, and builds the SessionFactory.

Key points to cover:

  • In Spring Boot, you never touch it. Boot configures JPA from spring.datasource.* and spring.jpa.* properties, and builds the EntityManagerFactory automatically.

Q10. What is the second-level cache?

Short answer: An optional cache shared across sessions, at the SessionFactory level, that stores entity data by ID. Repeat reads of the same entities from different transactions then skip the database. It's provided by a pluggable cache (Ehcache or Infinispan through JCache, or Hazelcast), and enabled per entity with @Cache.

Key points to cover:

  • The first-level cache is the per-session persistence context. It's always on, and short-lived.
  • The second-level cache suits read-mostly reference data (countries, product categories). It's risky for frequently updated data, and when other applications write to the same tables, the cache goes stale.
  • The query cache is separate, and only caches the IDs of query results.

Q11. What's the difference between get() and load()?

Short answer:

  • session.get() (JPA: em.find()) hits the database immediately (unless the entity is already in the persistence context), and returns null if the row doesn't exist.
  • session.load() (JPA: em.getReference()) returns a lazy proxy without querying. The query runs on first access to a non-ID property, and that is when an ObjectNotFoundException/EntityNotFoundException is thrown if the row is missing.
Order order = em.getReference(Order.class, orderId);   // no SELECT
line.setOrder(order);                                   // perfect for setting a foreign key without loading the Order

Key points to cover:

  • In Hibernate 6, load() is deprecated in favour of getReference(). Spring Data exposes it as getReferenceById().

Q12. How does Hibernate help ensure data integrity?

Short answer: Through transactions (atomic commit or rollback), database constraints that it maps (primary keys, foreign keys, unique and not-null constraints), optimistic locking with @Version to prevent lost updates, pessimistic locks (SELECT … FOR UPDATE) when needed, and Bean Validation checks before insert or update.

Key points to cover:

  • The database constraints are the final safety net. Keep them even when the application validates, because concurrent requests can pass application checks and still collide.

Follow-up questions this topic invites — and their answers

Q: What is dirty checking? A: At flush time, Hibernate compares every managed entity with the snapshot taken when it was loaded, and issues UPDATE statements for the changed ones. That's why save() isn't needed for managed entities inside a transaction.

Q: When does Hibernate flush? A: At transaction commit, before running a query whose results the pending changes could affect (in AUTO flush mode), or when you call flush() explicitly. A flush sends the SQL, but it doesn't commit.

Q: persist() vs merge()? A: persist makes a new transient entity managed. merge copies the state of a detached (or new) entity onto a managed instance, and returns that instance. The object you passed in stays detached.

Q: Why prefer FetchType.LAZY for @ManyToOne? A: @ManyToOne and @OneToOne default to EAGER in JPA, which silently loads related rows on every query, and causes N+1 problems. Declare them LAZY, and fetch explicitly when you need them.

Previous

Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Next

Hibernate Performance, Mapping & Scenarios — Interview Questions

AI Tutor

Lesson: Hibernate & JPA Core Concepts — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.