issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

Top 45 Hibernate Interview Questions 2026

19 min read
Interview Questions
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~20 min

Hibernate is the most widely used JPA implementation in Java applications. Candidates report that N+1 problem, lazy vs eager loading, caching, and entity relationships are the most frequently tested Hibernate topics in Java backend interviews.

Pair with Spring Framework Interview Questions 2026 and Java Interview Questions 2026. Confirm current interview requirements on the official careers portal of your target company.


Table of Contents

  1. Hibernate Fundamentals (Q1-Q12)
  2. Entity Mapping and Relationships (Q13-Q22)
  3. HQL, JPQL, and Criteria API (Q23-Q30)
  4. Caching and Performance (Q31-Q40)
  5. Advanced Topics (Q41-Q45)
  6. Mock Interview: 5 Questions
  7. FAQ

Hibernate Fundamentals

Q1. What is Hibernate and what problem does it solve? Easy

  • Manual SQL writing (generates SQL automatically)
  • ResultSet to object mapping (maps rows to Java objects)
  • Database portability (supports MySQL, PostgreSQL, Oracle via dialect)
  • Connection pooling and transaction integration
Java Class <---> Hibernate ORM <---> Database Table
User.java        SQL generation     users table

Q2. What is the difference between Hibernate and JPA? Easy

FeatureJPAHibernate
TypeSpecification (javax/jakarta.persistence)Implementation
Packagejakarta.persistence.*org.hibernate.*
UsageDefine entities, queries via standard APIProvides additional features on top of JPA
Other implsEclipseLink, DataNucleusN/A (Hibernate is one impl)
// JPA annotation (portable across implementations)
@Entity
@Table(name = "users")
public class User { }

// Hibernate-specific (only works with Hibernate)
@GenericGenerator(name = "uuid", strategy = "uuid2")

Prefer JPA annotations for portability. Use Hibernate-specific annotations only when needed.


Q3. What is a SessionFactory? Easy

// Hibernate native API
SessionFactory sessionFactory = new Configuration()
    .configure("hibernate.cfg.xml")
    .buildSessionFactory();

// In Spring (automatically created)
// spring.datasource.url=...
// spring.jpa.properties.hibernate.dialect=...
// EntityManagerFactory (JPA equivalent of SessionFactory)
@Autowired
EntityManagerFactory emf;
SessionFactory sf = emf.unwrap(SessionFactory.class);

Q4. What is a Session (and EntityManager)? Easy

// Hibernate native
try (Session session = sessionFactory.openSession()) {
    Transaction tx = session.beginTransaction();
    session.save(user);
    tx.commit();
}

// JPA (preferred in Spring projects)
@Autowired
EntityManager em;

@Transactional
void saveUser(User user) {
    em.persist(user);
}

Q5. What are entity states in Hibernate? Medium

StateDescriptionIn persistent context?Changes tracked?
TransientNew object, not savedNoNo
PersistentManaged by sessionYesYes (auto-flush)
DetachedWas persistent, session closedNoNo
RemovedMarked for deletionYesYes
User user = new User("Aditya");  // Transient
session.save(user);               // Persistent
session.close();                  // Detached
session.delete(user);             // Removed (within a session)

// Reattach detached entity
session.update(user);  // update (throws if already persistent)
session.merge(user);   // merge (safer - returns persistent copy)

Q6. What is the difference between save, persist, merge, update, and saveOrUpdate? Medium

MethodJPA equivalentBehavior
saveN/AStores transient, returns generated ID
persistpersistStores transient, void return
mergemergeCopies detached state, returns new managed instance
updateN/AReattach detached, throws if already managed
saveOrUpdateN/ASave if new, update if detached
// merge is safest for web flow (create -> submit -> save)
User detached = ...; // from HTTP request
User managed = session.merge(detached);  // correct

Q7. What is dirty checking in Hibernate? Medium

@Transactional
void updateName(Long id, String newName) {
    User user = em.find(User.class, id);  // fetched, now persistent
    user.setName(newName);  // modify
    // No explicit save needed!
    // Hibernate generates: UPDATE users SET name=? WHERE id=?
}

Hibernate compares current state to snapshot taken at load time. Changed fields trigger an UPDATE.


Q8. What is flush in Hibernate? Medium

FlushMode options:
// AUTO (default): flush before queries and at commit
// COMMIT: flush only at transaction commit
// ALWAYS: flush before every query (rarely needed)
// MANUAL: flush only when explicitly called

session.flush();  // force immediate sync
em.flush();       // JPA equivalent

// Setting flush mode
session.setHibernateFlushMode(FlushModeType.COMMIT);

Q9. What is the first-level cache? Medium

// Only ONE SQL query
User u1 = session.get(User.class, 1L);  // SQL: SELECT
User u2 = session.get(User.class, 1L);  // no SQL, returns same object
assert u1 == u2;  // true (same reference)

// Clear the cache
session.clear();         // clear all
session.evict(user);     // evict specific entity

The first-level cache is always on and cannot be disabled.


Q10. What is the difference between get and load? Medium

// get (find in JPA): immediate database hit, returns null if not found
User user = session.get(User.class, 999L);  // SQL executed immediately
if (user == null) { handle(); }

// load: returns proxy, SQL executed only on property access
// Throws ObjectNotFoundException if not found when accessed
User proxy = session.load(User.class, 999L);  // no SQL yet
proxy.getName();  // SQL executed here (or ObjectNotFoundException)

Use get/find when you're not sure if the entity exists. Use load as an optimization when you only need the ID (for associations).


Q11. Predict the output: Medium

// Assume user ID 1 exists in DB
Session session = sessionFactory.openSession();
User u1 = session.get(User.class, 1L);  // SQL executed
User u2 = session.get(User.class, 1L);  // No SQL

System.out.println(u1 == u2);           // ?
System.out.println(u1.equals(u2));      // ?

Output: true, true

Explanation: First-level cache returns the same object reference for the same session + ID. Both == and equals are true.


Q12. What is @GeneratedValue and its strategies? Easy

@Id
@GeneratedValue(strategy = GenerationType.AUTO)   // pick best for DB
@GeneratedValue(strategy = GenerationType.IDENTITY) // auto-increment column
@GeneratedValue(strategy = GenerationType.SEQUENCE) // DB sequence
@GeneratedValue(strategy = GenerationType.TABLE)   // separate table for IDs

// SEQUENCE with custom settings (PostgreSQL, Oracle)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "users_seq", allocationSize = 50)
private Long id;

Entity Mapping and Relationships

Q13. What is @OneToMany and @ManyToOne? Medium

@Entity
public class Department {
    @Id @GeneratedValue Long id;
    String name;
    
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Employee> employees = new ArrayList<>();
}

@Entity
public class Employee {
    @Id @GeneratedValue Long id;
    String name;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "department_id")
    private Department department;
}

mappedBy: tells Hibernate which side owns the foreign key (the department_id is in the employees table, so Employee owns the relationship).


Q14. What is @ManyToMany? Medium

@Entity
public class Student {
    @Id @GeneratedValue Long id;
    
    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(
        name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private Set<Course> courses = new HashSet<>();
}

@Entity
public class Course {
    @Id @GeneratedValue Long id;
    
    @ManyToMany(mappedBy = "courses")
    private Set<Student> students = new HashSet<>();
}

Q15. What are cascade types? Medium

CascadeTypeBehavior
PERSISTSave child when parent is saved
MERGEMerge child when parent is merged
REMOVEDelete child when parent is deleted
REFRESHRefresh child when parent is refreshed
DETACHDetach child when parent is detached
ALLAll of the above
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Address> addresses;

// orphanRemoval: true = delete Address if removed from list
addresses.remove(0);  // triggers DELETE for that address

Q16. What is lazy vs eager loading? Medium

// LAZY (default for collections): load only when accessed
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;  // SQL executed only when orders.get(0) or orders.size() called

// EAGER: load immediately with parent
@ManyToOne(fetch = FetchType.EAGER)  // default for @ManyToOne
private Department department;

// Summary of defaults:
// @ManyToOne: EAGER
// @OneToOne: EAGER
// @OneToMany: LAZY
// @ManyToMany: LAZY

Prefer LAZY everywhere, use JOIN FETCH in queries when you know you'll need related data.


Q17. What is the N+1 problem? Advanced

// PROBLEM: 1 + N queries
List<Department> depts = em.createQuery("SELECT d FROM Department d").getResultList();
// 1 query for departments

for (Department d : depts) {
    d.getEmployees().size();  // N queries! one per department
}

// SOLUTION 1: JOIN FETCH (one query)
List<Department> depts = em.createQuery(
    "SELECT DISTINCT d FROM Department d JOIN FETCH d.employees"
).getResultList();

// SOLUTION 2: EntityGraph
EntityGraph<Department> graph = em.createEntityGraph(Department.class);
graph.addAttributeNodes("employees");
List<Department> depts = em.createQuery("SELECT d FROM Department d")
    .setHint("jakarta.persistence.loadgraph", graph)
    .getResultList();

// SOLUTION 3: Batch fetching
@BatchSize(size = 25)
@OneToMany
private List<Employee> employees;

Q18. What is @Embeddable and @Embedded? Medium

@Embeddable
public class Address {
    String street;
    String city;
    String pincode;
}

@Entity
public class User {
    @Id Long id;
    String name;
    
    @Embedded
    private Address address;  // address columns go into users table
}

// Creates: users (id, name, street, city, pincode)
// Override column names:
@Embedded
@AttributeOverrides({
    @AttributeOverride(name = "street", column = @Column(name = "home_street"))
})
private Address homeAddress;

Q19. What is inheritance mapping in Hibernate? Advanced

// Strategy 1: SINGLE_TABLE (default, best performance)
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Payment { Long id; double amount; }

@Entity @DiscriminatorValue("CARD")
public class CardPayment extends Payment { String cardNumber; }

@Entity @DiscriminatorValue("UPI")
public class UpiPayment extends Payment { String upiId; }
// All in one table: payments(id, amount, type, cardNumber, upiId)

// Strategy 2: TABLE_PER_CLASS (no polymorphic queries)
// Strategy 3: JOINED (separate tables, joins on query)

Q20. What are @Column attributes? Easy

@Column(
    name = "email_address",  // column name
    nullable = false,         // NOT NULL constraint
    unique = true,            // UNIQUE constraint
    length = 255,             // VARCHAR(255)
    updatable = false,        // never updated after insert
    insertable = true
)
private String email;

@Column(precision = 10, scale = 2)  // DECIMAL(10,2)
private BigDecimal salary;

@Lob  // CLOB or BLOB
private String longDescription;

Q21. What is @Index and @UniqueConstraint? Medium

@Entity
@Table(
    name = "users",
    indexes = {
        @Index(name = "idx_users_email", columnList = "email"),
        @Index(name = "idx_users_name_dept", columnList = "name, department_id")
    },
    uniqueConstraints = @UniqueConstraint(columnNames = {"email"})
)
public class User { }

Q22. What are lifecycle callbacks? Medium

@Entity
public class User {
    @PrePersist
    void onSave() { createdAt = LocalDateTime.now(); }
    
    @PreUpdate
    void onUpdate() { updatedAt = LocalDateTime.now(); }
    
    @PostLoad
    void onLoad() { System.out.println("Loaded: " + id); }
    
    @PreRemove
    void onDelete() { System.out.println("Deleting: " + id); }
    
    @PostPersist
    void afterSave() { System.out.println("Saved with id: " + id); }
}

HQL, JPQL, and Criteria API

Q23. What is HQL/JPQL? Medium

// HQL/JPQL: object-oriented query language (not SQL)
// Operates on entity classes and fields, not tables and columns

String jpql = "SELECT u FROM User u WHERE u.age > :minAge ORDER BY u.name";
List<User> users = em.createQuery(jpql, User.class)
    .setParameter("minAge", 18)
    .setMaxResults(10)
    .getResultList();

// Projections (DTO query)
String projectionJpql = "SELECT new com.example.UserDTO(u.name, u.email) FROM User u";
List<UserDTO> dtos = em.createQuery(projectionJpql, UserDTO.class).getResultList();

// Aggregate
String aggJpql = "SELECT dept.name, COUNT(emp) FROM Employee emp JOIN emp.department dept GROUP BY dept.name";
List<Object[]> results = em.createQuery(aggJpql).getResultList();

Q24. What is the Criteria API? Advanced

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> user = cq.from(User.class);

// WHERE age > 18 AND name LIKE 'A%'
Predicate agePred = cb.greaterThan(user.get("age"), 18);
Predicate namePred = cb.like(user.get("name"), "A%");

cq.select(user)
  .where(cb.and(agePred, namePred))
  .orderBy(cb.asc(user.get("name")));

List<User> results = em.createQuery(cq).getResultList();

Criteria API is type-safe and ideal for dynamic queries where conditions are built at runtime.


Q25. What is a named query? Medium

@Entity
@NamedQuery(name = "User.findActive",
            query = "SELECT u FROM User u WHERE u.active = true ORDER BY u.name")
@NamedQuery(name = "User.findByEmail",
            query = "SELECT u FROM User u WHERE u.email = :email")
public class User { }

// Usage
List<User> active = em.createNamedQuery("User.findActive", User.class).getResultList();
Optional<User> user = em.createNamedQuery("User.findByEmail", User.class)
    .setParameter("email", "[email protected]")
    .getResultStream()
    .findFirst();

Q26. What is a native SQL query in Hibernate? Medium

// For database-specific queries not expressible in JPQL
List<User> users = em.createNativeQuery(
    "SELECT * FROM users WHERE MATCH(name, bio) AGAINST(:search IN BOOLEAN MODE)",
    User.class
).setParameter("search", "java developer").getResultList();

// With manual mapping
List<Object[]> rows = em.createNativeQuery(
    "SELECT u.name, COUNT(o.id) FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id"
).getResultList();

Q27. What is JOIN FETCH vs regular JOIN? Advanced

// Regular JOIN: filters results but does NOT load employees (still lazy)
String regular = "SELECT d FROM Department d JOIN d.employees e WHERE e.salary > 50000";

// JOIN FETCH: loads employees into memory (solves N+1 for the query)
String fetch = "SELECT DISTINCT d FROM Department d JOIN FETCH d.employees e WHERE e.salary > 50000";

// Warning: JOIN FETCH with pagination is problematic
// Hibernate shows HHH90003004 warning when combining FETCH + setMaxResults
// Solution: use subquery or separate query

Q28. What is @Query in Spring Data JPA? Medium

public interface UserRepository extends JpaRepository<User, Long> {
    
    @Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true")
    Optional<User> findActiveByEmail(@Param("email") String email);
    
    @Query("SELECT u FROM User u WHERE u.createdAt BETWEEN :from AND :to")
    List<User> findCreatedBetween(
        @Param("from") LocalDate from,
        @Param("to") LocalDate to
    );
    
    @Modifying
    @Query("UPDATE User u SET u.active = false WHERE u.lastLogin < :cutoff")
    int deactivateInactiveUsers(@Param("cutoff") LocalDate cutoff);
}

Q29. What is Specification in Spring Data? Advanced

// Dynamic queries via Specification (Criteria API wrapper)
public class UserSpecifications {
    public static Specification<User> hasName(String name) {
        return (root, query, cb) -> 
            name == null ? null : cb.like(root.get("name"), "%" + name + "%");
    }
    
    public static Specification<User> isActive() {
        return (root, query, cb) -> cb.isTrue(root.get("active"));
    }
}

// Usage
List<User> users = userRepo.findAll(
    Specification.where(hasName("Aditya")).and(isActive())
);

Q30. Predict the output: Medium

// Department has employees (LAZY)
// employeeCount: how many SQL queries?
List<Department> depts = em.createQuery("SELECT d FROM Department d").getResultList();
for (Department d : depts) {
    System.out.println(d.getName() + ": " + d.getEmployees().size());
}

Output: Results for each department, but this executes 1 + N SQL queries.

Explanation: 1 query fetches departments. For each of N departments, accessing d.getEmployees() triggers a separate SQL query. Fix: use JOIN FETCH d.employees or @BatchSize.


Caching and Performance

Q31. What is the second-level cache? Advanced

// Enable (requires cache provider like Ehcache or Hazelcast)
// hibernate.cfg.xml:
// hibernate.cache.use_second_level_cache=true
// hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheCacheRegionFactory

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country { }  // Cached in L2

// Read-only: best performance for immutable data
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Currency { }

Q32. What is query cache? Advanced

// Cache query results (not just entities)
// hibernate.cache.use_query_cache=true

List<Country> countries = session.createQuery("FROM Country ORDER BY name")
    .setCacheable(true)
    .setCacheRegion("country_list")
    .list();
// Second call with same query: returns from cache

Query cache stores query results as ID lists. Invalidated when any entity in the result set changes.


Q33. What is connection pooling and why is it needed? Medium

// HikariCP (default in Spring Boot)
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000  // 30 seconds
spring.datasource.hikari.idle-timeout=600000        // 10 minutes
spring.datasource.hikari.max-lifetime=1800000       // 30 minutes

Q34. How do you avoid LazyInitializationException? Advanced

// LazyInitializationException: accessing lazy collection outside session

// WRONG
User user = userService.findById(1L);  // session closed after service
user.getOrders().size();  // BOOM: no session

// FIX 1: JOIN FETCH in query
@Query("SELECT u FROM User u JOIN FETCH u.orders WHERE u.id = :id")
Optional<User> findByIdWithOrders(@Param("id") Long id);

// FIX 2: @Transactional on the calling code
@Transactional(readOnly = true)
void processUser(Long id) {
    User user = userRepo.findById(id).get();
    user.getOrders().size();  // ok, session still open
}

// FIX 3: Hibernate.initialize()
Hibernate.initialize(user.getOrders());  // force load within session

// FIX 4: spring.jpa.open-in-view=true (antipattern - avoid)

Q35. What is @BatchSize for performance? Advanced

// Instead of N queries, loads in batches of N
@Entity
public class Department {
    @OneToMany
    @BatchSize(size = 25)
    private List<Employee> employees;
}
// Accessing employees for 100 departments: ~4 queries (100/25) instead of 100

Q36. What is an entity graph? Advanced

// Define at entity level
@Entity
@NamedEntityGraph(
    name = "User.withOrders",
    attributeNodes = @NamedAttributeNode(value = "orders",
        subgraph = "orders.items"),
    subgraphs = @NamedSubgraph(name = "orders.items",
        attributeNodes = @NamedAttributeNode("items"))
)
public class User { }

// Usage in Spring Data
@EntityGraph(value = "User.withOrders", type = EntityGraphType.LOAD)
Optional<User> findById(Long id);

Q37. What is the difference between readOnly = true and regular transaction? Medium

@Transactional(readOnly = true)
List<User> getAllUsers() {
    return userRepo.findAll();
}
// readOnly = true:
// 1. Hibernate skips dirty checking (no snapshot comparison)
// 2. Database can use read replicas
// 3. Flush mode set to NEVER
// Result: faster reads, less memory

Q38. What is @OptimisticLocking? Advanced

@Entity
public class Product {
    @Id Long id;
    String name;
    int stock;
    
    @Version  // Optimistic lock via version column
    int version;
}

// Thread A and Thread B both read Product{id=1, version=5, stock=10}
// Thread A: updates stock=9, version becomes 6
// Thread B: tries to update stock=9 with version=5
// -> Hibernate detects version mismatch -> throws OptimisticLockException

Q39. What is pessimistic locking? Advanced

// Lock row at query time (SELECT ... FOR UPDATE)
User user = em.find(User.class, id, LockModeType.PESSIMISTIC_WRITE);
// Database lock prevents other transactions from reading/writing until this tx commits

// In Spring Data
@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<User> findById(Long id);

Use pessimistic locking for high-contention resources where conflicts are frequent. Optimistic for low-contention.


Q40. What is the statistics feature in Hibernate? Advanced

// Enable in properties
hibernate.generate_statistics=true

// Programmatically
Statistics stats = sessionFactory.getStatistics();
System.out.println("Query count: " + stats.getQueryExecutionCount());
System.out.println("L2 cache hits: " + stats.getSecondLevelCacheHitCount());
System.out.println("Entity loads: " + stats.getEntityLoadCount());

// In Spring Boot, expose via Actuator metrics
management.endpoints.web.exposure.include=metrics
# /actuator/metrics/hibernate.query.executions.total

Advanced Topics

Q41. What is @NaturalId? Medium

@Entity
public class User {
    @Id @GeneratedValue Long id;  // surrogate key
    
    @NaturalId
    @Column(unique = true, nullable = false)
    String email;  // natural identifier
}

// Load by natural ID (uses cache)
User user = session.byNaturalId(User.class)
    .using("email", "[email protected]")
    .load();

Q42. What is multi-tenancy in Hibernate? Advanced

  • Schema-based: each tenant in separate schema
  • Database-based: each tenant in separate database
  • Discriminator-based: all tenants share tables, filtered by tenant column
@Entity
@TenantId
@Column(name = "tenant_id")
String tenantId;  // automatically filtered by Hibernate

Q43. What is Hibernate Validator? Medium

// Hibernate Validator is the reference implementation of Bean Validation (JSR-380)
import jakarta.validation.constraints.*;

public class User {
    @NotBlank
    @Size(min = 2, max = 50)
    String name;
    
    @Email
    @NotNull
    String email;
    
    @Min(18) @Max(120)
    int age;
    
    @Past
    LocalDate birthDate;
    
    @Pattern(regexp = "^\\+91[0-9]{10}$")
    String phone;
}

Q44. What is the @Formula annotation? Advanced

@Entity
public class Employee {
    @Id Long id;
    double baseSalary;
    
    @Formula("base_salary * 1.2")
    double grossSalary;  // computed column, read-only
    
    @Formula("(SELECT COUNT(*) FROM projects p WHERE p.manager_id = id)")
    int projectCount;  // subquery formula
}

Q45. What are common Hibernate performance anti-patterns? Advanced

Anti-patternProblemFix
N+1 queriesN extra queries for lazy collectionsJOIN FETCH, @BatchSize, EntityGraph
EAGER everywhereLoads all associations alwaysUse LAZY, fetch explicitly
SELECT * with @FormulaComputes unnecessary formulas@Basic(fetch=LAZY) on expensive formulas
Missing indexesFull table scan on every queryAdd @Index on frequently queried columns
Large batch inserts without flushOutOfMemoryErrorFlush and clear every N records
// Correct batch insert pattern
for (int i = 0; i < 10000; i++) {
    session.persist(new Entity(i));
    if (i % 50 == 0) {  // flush and clear every 50
        session.flush();
        session.clear();
    }
}

Mock Interview: 5 Questions

  1. Explain the N+1 problem with a concrete example and show three different ways to fix it.
  2. What is the difference between session.merge() and session.update()? When would you use each?
  3. A team member complains the application is slow after adding a new entity relationship. How do you diagnose whether it is an N+1 problem?
  4. What happens if you call session.get() for the same entity ID three times in the same session?
  5. Explain first-level vs second-level cache with a diagram description.

FAQ

Q: Do I need to learn Hibernate separately if I know Spring Data JPA? A: Yes. Spring Data JPA adds a convenient repository layer, but Hibernate behavior (lazy loading, caching, N+1) happens underneath. Knowing Hibernate internals is essential for debugging and performance tuning.

Q: When should I use native SQL vs JPQL? A: Use JPQL for standard queries - it's portable and entity-aware. Use native SQL for database-specific features (full-text search, window functions, stored procedures) or when you need to optimize with database-specific hints.

Q: Is Hibernate still used, or is there a better alternative? A: Hibernate via Spring Data JPA remains the dominant ORM in Java. JOOQ is a popular alternative for teams that prefer type-safe SQL over HQL. For simple CRUD, Spring Data JPA with Hibernate is the standard.


Related reading: Spring Framework Interview Questions 2026 | Spring Boot Interview Questions 2026 | Java Interview Questions 2026 | SQL Interview Questions 2026

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: