Friday, 13 June 2025

Hibernate Framework

 

✅ 1. What is the Advantage of Hibernate over JDBC?

Hibernate offers several powerful advantages over traditional JDBC:

#HibernateJDBC
1️⃣Database IndependenceHibernate abstracts DB-specific queries. Works across MySQL, Oracle, PostgreSQL, etc.
2️⃣Object-Oriented DesignTreats tables as Java objects (POJOs).
3️⃣No Need to Learn SQLWith HQL/Criteria API, most work is done in Java.
4️⃣Automatic Query OptimizationHibernate optimizes queries automatically via Criteria API.
5️⃣Caching SupportSupports 1st and 2nd level cache for performance.
6️⃣Faster DevelopmentLess boilerplate code, faster CRUD development.
7️⃣Connection Pooling SupportSupports C3P0, HikariCP, etc.
8️⃣Mapping & Relations in XML/AnnotationsEasier to visualize and maintain object relationships.
9️⃣Lazy Loading SupportLoad data on demand (lazy=false for eager).
🔟Versioning and Optimistic LockingBuilt-in version control of DB rows.

✅ 2. What is Hibernate?

Hibernate is:

  • A lightweight ORM (Object Relational Mapping) framework for Java.

  • Used to map Java classes (POJOs) to database tables.

  • Aims to simplify database operations like saving, retrieving, updating, and deleting objects.

  • Abstracts JDBC complexities like connection management, SQL statements, and transactions.


✅ 3. What is ORM?

ORM (Object Relational Mapping) is a technique that:

  • Connects Java classes to database tables.

  • Maps Java fields to table columns.

  • Handles conversion between Java types and SQL types.

Think of ORM as a bridge between Java objects and relational data.


✅ 4. What Does ORM Consist Of?

An ORM framework like Hibernate typically includes:

  • API for CRUD operations (save(), update(), delete(), etc.)

  • Query Language like HQL (Hibernate Query Language)

  • Metadata Mapping via XML or Annotations (@Entity, @Table, @Column)

  • Optimization features like:

    • Lazy loading

    • Dirty checking

    • Cascading

    • Batch fetching


✅ 5. What are the ORM Levels?

LevelDescription
1️⃣ Pure RelationalSQL and stored procedures only
2️⃣ Light Object MappingJDBC with basic mapping to POJOs
3️⃣ Medium Object MappingSome OOP concepts like inheritance
4️⃣ Full Object MappingFull OOP support with relationships, inheritance, lazy loading, etc. — Hibernate lies here

✅ 6. Why Use ORM Tools like Hibernate?

BenefitExplanation
🔁 DB IndependenceWrite code once, use with any supported DB.
💡 ProductivityLess boilerplate code, use HQL instead of SQL.
🚀 PerformanceBuilt-in caching, lazy/eager loading.
🔄 MaintainabilityLess coupling, easier to refactor.
🌍 PortabilitySQL is DB-specific, Hibernate handles the translation.

✅ 7. What Does Hibernate Simplify?

Hibernate removes much of the complexity in persistence code:

  • Saving and loading Java objects.

  • Mapping DB columns and tables to Java code.

  • Managing transactions and connections.

  • Executing joins and queries via object navigation.

  • Generating DB schema from object model.


✅ 8. Difference Between Hibernate and Entity Beans (EJB)

FeatureHibernateEntity Beans (EJB)
DB SupportMultiple DBs via configLimited DB support
ContainerNo special container neededRequires EJB container
OOP SupportFull support (inheritance, polymorphism)Limited
CachingBuilt-in multilevel cacheNot supported
Connection PoolingUses C3P0, Hikari, etc.Manual setup
PortabilityLightweight & portableHeavy, tied to container

✅ 9. Core Interfaces and Classes in Hibernate

Interface/ClassPurpose
ConfigurationLoads config file & mapping (hibernate.cfg.xml)
SessionFactorySingleton factory for sessions, created once per app
SessionMain interface to interact with DB, represents unit of work
TransactionUsed to begin, commit, or rollback transactions
Query / CriteriaFor fetching data via HQL, native SQL, or Criteria API

✅ 10. Hibernate Execution Flow

  1. Load Configuration

    Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
  2. Build SessionFactory

    SessionFactory sessionFactory = cfg.buildSessionFactory();
  3. Open Session

    Session session = sessionFactory.openSession();
  4. Begin Transaction

    Transaction tx = session.beginTransaction();
  5. Perform Operation

    session.save(entity);
  6. Commit and Close

    tx.commit();
    session.close();
11. What is the need for Hibernate Mapping File?

The Hibernate mapping file (*.hbm.xml) is used to map Java class fields to database table columns. It tells Hibernate:

  • Which class corresponds to which table

  • Which class fields map to which table columns

  • How the primary key is generated

  • The types of relationships (one-to-many, many-to-one, etc.)

  • Whether lazy loading is enabled

  • Cascade options

Key roles:

  • Define table name, column names, data types, length, nullability

  • Specify primary key with <id>

  • Specify associations like <many-to-one>, <one-to-many>, etc.

  • Configure fetch strategy (lazy, eager)

  • Define generators (increment, identity, sequence, uuid)

Example:

Employee.hbm.xml
<hibernate-mapping>
<class name="com.sample.Employee" table="EMPLOYEE"> <id name="id" column="EMP_ID"> <generator class="increment"/> </id> <property name="name" column="EMP_NAME"/> <property name="address" column="EMP_ADDRESS"/> </class> </hibernate-mapping>

12. What are the important tags of hibernate.cfg.xml?

This configuration file tells Hibernate how to connect to the database and where to find mapping files or annotated classes.

Key tags:

  • <hibernate-configuration>: Root element

  • <session-factory>: Defines all settings under it

    • <property name="hibernate.connection.driver_class">

    • <property name="hibernate.connection.url">

    • <property name="hibernate.connection.username">

    • <property name="hibernate.connection.password">

    • <property name="hibernate.dialect">

    • <property name="hibernate.hbm2ddl.auto"> – create, update, validate, none

    • <property name="hibernate.show_sql">

    • <mapping resource="Employee.hbm.xml"/> – for XML mappings

    • <mapping class="com.sample.Employee"/> – for annotated classes

Example:

hibernate.cfg.xml

<hibernate-configuration>
<session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.show_sql">true</property> <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration>

13. What role does the Session interface play in Hibernate?

Session is the main interface to interact with the database using Hibernate. It’s not threadsafe, and represents a single unit of work or conversation.

Key roles:

  • Open connection to DB

  • Perform CRUD operations

  • Create queries

  • Manage object states (persistent, detached, transient)

  • Start and manage transactions

  • Acts as a first-level cache (mandatory)

Example:

java
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction(); Employee e = session.get(Employee.class, 1); // Read session.save(new Employee("John")); // Create session.delete(e); // Delete tx.commit(); session.close();

14. What role does the SessionFactory interface play in Hibernate?

SessionFactory is a thread-safe, heavyweight object responsible for:

  • Creating Session instances

  • Caching mappings, SQL, and metadata

  • Acting as a second-level cache provider

  • Created once per application (usually singleton)

Characteristics:

  • Immutable

  • Created using Configuration object

  • Expensive to create

Example:

java
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml") .buildSessionFactory(); Session session = factory.openSession();

15. What are the most common ways to specify the Hibernate configuration properties?

1. XML (hibernate.cfg.xml):

Most traditional and complete.

2. Java Properties file (hibernate.properties):

Simple key-value pair format.

3. Programmatic configuration:

Using Configuration object directly in Java.

java
Configuration cfg = new Configuration();
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost/test");

4. Annotations:

From Hibernate 3.3 onwards, JPA annotations are supported directly in entity classes.

Employee.java
@Entity
@Table(name = "EMPLOYEE") public class Employee { ... }

16. How do you map Java objects with DB tables?

Steps:

  1. Create Java Bean (POJO with setters/getters)

  2. Create mapping file (*.hbm.xml)

  3. Define class-to-table and property-to-column mappings

Example:

Employee.hbm.xml
<hibernate-mapping>
<class name="com.sample.EmployeeBean" table="EMPLOYEE"> <id name="eid" column="ID"/> <property name="ename" column="NAME" length="255" not-null="true"/> <property name="address" column="ADDR" length="255" not-null="true"/> </class> </hibernate-mapping>

17. How do you define sequence-generated primary key in Hibernate?

You use the <id> tag and <generator> subtag.

Example using Oracle/Postgres sequence:

xml
<id name="userid" column="USER_ID" type="long"> <generator class="sequence"> <param name="sequence">USER_SEQ</param> </generator> </id>

Other generator strategies:

  • increment – auto-increment, simple

  • identity – DB-specific auto-increment (MySQL)

  • sequence – uses DB sequence (Oracle, PostgreSQL)

  • uuid – universally unique identifier


18. What is component mapping in Hibernate?

A component (also called embedded) is a value-type object stored with the entity in the same table.

Features:

  • No separate table

  • No primary key needed for component

  • Used with @Embeddable and @Embedded in annotations

  • Requires a no-arg constructor

  • Shared references not supported

XML Example:

xml
<component name="address" class="Address">
<property name="city"/> <property name="state"/> </component>

Annotation Example:

java
@Embeddable
public class Address { private String city; private String state; } @Entity public class Employee { @Embedded private Address address; }

19. Difference between getCurrentSession() and openSession() in Hibernate?

FeaturegetCurrentSession()openSession()
Session managementManaged by Hibernate (bound to transaction)Manual (you must close it explicitly)
Auto closeYesNo
Auto flushYesNo
Thread safeNot safe across threadsNot safe across threads
Use caseBest in JTA or Spring transactionsUse when manual control is needed

Example with openSession():
Session session = factory.openSession();
Transaction tx = session.beginTransaction(); // operations tx.commit(); session.close(); // Manual

Example with getCurrentSession():

Session session = factory.getCurrentSession(); // auto-close handled by framework

20. What are the types of Hibernate instance states?

1. Transient

  • Not associated with Hibernate session

  • No representation in database yet

  • Example: Employee e = new Employee();

2. Persistent

  • Associated with active session

  • Mapped to DB record

  • Changes automatically synchronized

  • Example: session.save(e);

3. Detached

  • Once persistent, but session closed

  • Not tracked anymore

  • Can be reattached using update(), merge()

21. What are the types of inheritance models in Hibernate?

Hibernate supports three types of inheritance mapping strategies for mapping Java class hierarchies to database tables:

  1. Table Per Class Hierarchy (Single Table Strategy)

    • All classes in the hierarchy are mapped to a single table.

    • A discriminator column is used to identify the subclass.

    • Pros: Fast queries, less joins.

    • Cons: Null values for non-shared fields of subclasses.

    java

    @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="type", discriminatorType = DiscriminatorType.STRING)
  2. Table Per Subclass (Joined Strategy)

    • Each class has its own table, but subclass tables contain only subclass fields and reference the superclass table using a foreign key.

    • Pros: Normalized structure, no nulls.

    • Cons: More joins when querying subclass data.

    java

    @Inheritance(strategy = InheritanceType.JOINED)
  3. Table Per Concrete Class (Table Per Class Strategy)

    • Each concrete class has its own table including all inherited properties.

    • No shared table for common fields.

    • Pros: No joins required.

    • Cons: Data duplication across tables.

    java

    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

22. What is Hibernate Query Language (HQL)?

  • HQL is an object-oriented query language similar to SQL but operates on Hibernate entity objects, not database tables.

  • It is database independent—you don’t write queries using actual table/column names.

  • HQL lets you:

    • Fetch objects (from Employee e)

    • Perform joins

    • Use aggregate functions (sum, count)

    • Write subqueries

Example:

java

List<Employee> employees = session.createQuery("FROM Employee WHERE salary > :minSal") .setParameter("minSal", 50000) .list();

23. What are the ways to express joins in HQL?

HQL supports multiple ways to represent inner and outer joins:

  1. Implicit Association Join

    • Automatically joins based on mapped relationships.

    java

    from Department d where d.employees.size > 5
  2. Explicit Join in FROM Clause

    • Manual join with optional join or left join.

    java

    from Department d join d.employees e
  3. Fetch Join

    • Used to initialize associated entities eagerly.

    java

    from Department d join fetch d.employees
  4. Theta-Style Join (in WHERE clause)

    • Traditional SQL-style join using conditions.

    java

    from Employee e, Department d where e.deptId = d.id

24. Transaction with plain JDBC in Hibernate

If not using a Java Transaction API (JTA), Hibernate supports JDBC-based transaction demarcation using its Transaction API.

Steps:

  1. Begin transaction with session.beginTransaction().

  2. Perform DB operations.

  3. Commit or rollback.

  4. Always close the session.

Example:

java

Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.load(Employee.class, 1); session.persist(new Employee()); tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; } finally { session.close(); }

Configuration:

properties

hibernate.transaction.factory_class = org.hibernate.transaction.JDBCTransactionFactory hibernate.current_session_context_class = thread

25. Best Practices for Defining Hibernate Persistent Classes

  1. Default Constructor

    • Required by Hibernate to instantiate objects via reflection.

    java

    public Employee() {}
  2. Getter and Setter Methods

    • Hibernate uses these to read/write fields.

  3. equals() and hashCode()

    • Use business keys (like email/SSN), not auto-generated IDs.

    • IDs might be null before saving to DB.

  4. Serializable Interface

    • Enables caching, session replication in clusters.

    java

    public class Employee implements Serializable {}
  5. Avoid Final Classes

    • Final classes prevent Hibernate from using proxies for lazy loading.

  6. session.update() vs. session.lock()

    • update(): Reattaches and updates the DB.

    • lock(): Reattaches only, no DB update.

    • Use lock() only if you're sure the DB is in sync with the object.


26. What are the Collection types in Hibernate?

Hibernate supports several collection mappings for one-to-many or many-to-many relationships:

  • Set: No duplicates, unordered.

  • List: Ordered, duplicates allowed.

  • Array: Fixed size.

  • Map: Key-value pairs.

  • Bag: Unordered collection allowing duplicates (like List without index column).


27. Sorted Collection vs. Ordered Collection

FeatureSorted CollectionOrdered Collection
Sorting LocationJava (in-memory)Database
MechanismJava ComparatorSQL ORDER BY
EfficiencyBest for small collectionsBest for large datasets
Annotation/Config@SortComparator@OrderBy

Example:
java

@SortComparator(MyComparator.class) private SortedSet<Employee> employees; @OrderBy("name ASC") private List<Employee> employees;

28. What do you mean by Named – SQL Query?

  • Named SQL queries are native SQL queries (not HQL) defined once in the XML mapping or annotations, and reused throughout the application.

XML Definition:

xml

<sql-query name="empdetails"> <return alias="emp" class="com.sample.Employee"/> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee emp WHERE emp.NAME LIKE :name </sql-query>

Invocation in Java:

java

List<Employee> people = session.getNamedQuery("empdetails") .setString("name", "TomBrady") .setMaxResults(50) .list();

29. How do you invoke Stored Procedures in Hibernate?

Hibernate allows stored procedure calls using named SQL queries with callable="true".

Example Configuration (in mapping XML):

xml

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee"> <return-property name="empid" column="EMP_ID"/> <return-property name="name" column="EMP_NAME"/> <return-property name="address" column="EMP_ADDRESS"/> { ? = call selectAllEmployees() } </return> </sql-query>
  • callable="true": Indicates it's a stored procedure.

  • { ? = call selectAllEmployees() }: Syntax for invoking a stored procedure that returns a result set.

  • return-property: Maps the result columns to Java fields.

Usage in Java:

java

List<Employee> employees = session.getNamedQuery("selectAllEmployees_SP").list();

30. Explain Criteria API

The Criteria API is a simplified, object-oriented API for creating queries in Hibernate.

  • It allows constructing complex queries using Java objects rather than SQL strings.

  • Useful when you don’t know query structure at compile time (e.g., advanced search filters).

  • Introduced via org.hibernate.Criteria (deprecated after Hibernate 5 in favor of JPA Criteria API).

Syntax Example:

List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%")) .add(Restrictions.eq("address", "Boston")) .addOrder(Order.asc("name")) .list();
  • Restrictions: Adds WHERE clause conditions.

  • Order.asc: Adds ORDER BY clause.

  • list(): Executes the query and returns results.

31.What’s the difference between load() and get()?

Both load() and get() are used in Hibernate to retrieve an object based on its primary key (ID), but they behave differently in terms of how and when they access the database.

load() Method:

  • Returns a proxy object initially.

  • Database is not hit until a method is called on the proxy (lazy loading).

  • If the object is not found in the database when accessed, it throws ObjectNotFoundException.

  • Should be used only when you're sure the record exists.

Example:

Employee emp = session.load(Employee.class, 100); // returns proxy
System.out.println(emp.getName()); // DB hit happens here

get() Method:

Immediately hits the database when invoked. If the entity with the given ID is not found, it returns null. Useful when you’re not sure if the record exists. No proxy is involved; actual object is returned.

Example:

java
Employee emp = session.get(Employee.class, 100); // immediately fetches from DB
if(emp == null) { System.out.println("Employee not found."); }
Key Differences Table:
Feature get() load()
Return Type Actual object Proxy object
Database Hit Immediately Only when accessed
Null Handling Returns null if not found Throws ObjectNotFoundException
Use Case When record may not exist When record definitely exists
Performance (initial load) Slower (eager) Faster (lazy, proxy-based)
32.What is the difference between and merge and update ?

These methods are used to reattach a detached object (an object that was once in a Hibernate session but the session is now closed).

update():

  • Reattaches a detached object to a session.

  • Fails with NonUniqueObjectException if the session already contains an object with the same identifier.

  • Doesn't return anything.

  • Use it only if you are sure the session doesn't already contain that entity.

Example:

java
session.update(employee);

merge():

  • Merges the state of a detached object with a persistent instance in the session.

  • Does not fail even if an object with the same ID already exists in the session.

  • Returns a managed (persistent) instance.

  • Safest method to reattach a detached object.

Example:

java
Employee updatedEmp = (Employee) session.merge(employee);

Key Differences:

Featureupdate()merge()
Behavior Reattaches a detached objectCopies detached state into new one
Exception Risk May throw NonUniqueObjectExceptionSafe
Return Type voidReturns managed instance
Use Case  Only if you're sure it's detachedPreferred for safety

33.Define cascade and inverse option in one-to-many mapping?

cascade:

  • Tells Hibernate what operations should propagate from parent to child entities.

  • For example, if you save/delete a parent, should Hibernate also save/delete its children?

  • Used in both XML and annotation-based configurations.

Options:

  • all

  • save-update

  • persist

  • merge

  • delete

  • delete-orphan

  • all-delete-orphan

Example (XML):

xml
<set name="children" cascade="all" />

inverse:

  • Used in bidirectional relationships to define the owner of the relationship.

  • inverse="true" indicates that the child side maintains the foreign key.

  • Prevents Hibernate from issuing unnecessary updates from both sides.

Example:

xml
<set name="children" inverse="true" />

Why It Matters:

Without inverse, both parent and child may try to maintain the foreign key, causing redundant or conflicting updates.

34.Define HibernateTemplate?

HibernateTemplate is a helper class provided by Spring (org.springframework.orm.hibernate5.HibernateTemplate) to simplify data access using Hibernate.

  • Wraps Hibernate’s SessionFactory.

  • Provides template methods for common operations.

  • Handles resource management (like session opening/closing) automatically.


35.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
 HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
 Common functions are simplified to single method calls.
 Sessions are automatically closed.
 Exceptions are automatically caught and converted to runtime exceptions.

HibernateTemplate is a helper class provided by the Spring Framework (part of org.springframework.orm.hibernate5) that simplifies data access code using Hibernate. It follows the Template Method design pattern and handles repetitive boilerplate code such as opening/closing sessions, handling transactions, and translating exceptions.

It is typically used in Spring + Hibernate integration to simplify DAO (Data Access Object) operations.


🔷 Core Benefits of HibernateTemplate with Detailed Explanation and Examples


✅ 1. Simplifies Interactions with Hibernate Session

Hibernate operations like save, update, delete, and get require boilerplate code using Session, Transaction, and proper try-catch-finally blocks. HibernateTemplate encapsulates all that internally.


🔸 Example Without HibernateTemplate:

public void saveEmployee(Employee emp) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(emp); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } }

🔸 Example With HibernateTemplate:

@Autowired private HibernateTemplate hibernateTemplate; public void saveEmployee(Employee emp) { hibernateTemplate.save(emp); }

🔹 Benefit: Just one line replaces multiple lines of session, transaction, and exception-handling code.


✅ 2. Common Functions Are Simplified to Single Method Calls

HibernateTemplate provides convenient one-liner methods for common database operations.

OperationHibernateTemplate Method
Savesave(Object entity)
Updateupdate(Object entity)
Deletedelete(Object entity)
Retrieveget(Class, Serializable)
List AllloadAll(Class)

🔸 Example: Load all Employees

java

List<Employee> employees = hibernateTemplate.loadAll(Employee.class);

✅ 3. Automatic Session Management

You don’t need to manually manage Session objects. It internally opens, flushes, and closes the session, so you avoid common mistakes like session leaks or forgetting to close.


✅ 4. Automatic Exception Translation

Hibernate throws checked exceptions like HibernateException. HibernateTemplate converts these into Spring’s runtime DataAccessException, which is part of a unified exception hierarchy in Spring.

This means:

  • No need to catch or declare checked exceptions.

  • Exception handling becomes easier and consistent across the DAO layer.


🔸 Example:

try { hibernateTemplate.save(emp); } catch (DataAccessException ex) { // Handle exception without worrying about checked HibernateException }

✅ 5. Integration with Spring Transactions

HibernateTemplate works well with Spring’s @Transactional annotation. You can define transaction boundaries declaratively at the service layer.


🔸 Example:

@Transactional public void updateEmployee(Employee emp) { hibernateTemplate.update(emp); }

This ensures:

  • Automatic rollback on exceptions.

  • Commit if no exception is thrown.


✅ 6. Support for Callback Programming (HibernateCallback)

For complex queries or operations, you can pass a custom implementation of HibernateCallback to execute() method, gaining full access to Session object.


🔸 Example:

java
List<Employee> result = hibernateTemplate.execute(session -> session.createQuery("from Employee where salary > 50000", Employee.class).list() );

🔹 Benefit: You still get session and exception management while using advanced features.


✅ 7. Clean and Readable DAO Code

By abstracting away boilerplate, HibernateTemplate allows you to write clean, concise, and maintainable DAO classes.


✅ Summary Table: Benefits of HibernateTemplate

BenefitExplanation
Simplified Hibernate interactionOne-liner for common operations like save, get, update
Automatic session managementNo need to manually open/close sessions
Auto exception translationConverts Hibernate exceptions to Spring's DataAccessException
Integrated with Spring AOPWorks with @Transactional
Callback supportAllows advanced queries with HibernateCallback
Encourages best practicesCleaner, safer, and reusable code patterns

⚠️ Note on Modern Usage

  • HibernateTemplate was widely used with Hibernate 3 and 4.

  • In modern Spring Boot applications, it's largely replaced by Spring Data JPA (JpaRepository), which offers even more abstraction.

  • However, HibernateTemplate is still relevant in legacy systems and for understanding underlying data access design patterns.


36. How do you switch between relational databases without code changes?

Hibernate abstracts database access via dialects, allowing you to switch databases without changing code.

Configuration:

xml
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

Examples of Dialects:

  • MySQLDialect

  • OracleDialect

  • SQLServerDialect

  • PostgreSQLDialect

Hibernate generates database-specific SQL internally based on the dialect.


37.If you want to see the Hibernate generated SQL statements on console, what should we do?

To print Hibernate SQL queries on console:

In XML file:

we need to below tag like
<property name="hibernate.show_sql">true</property>

In application.properties file:

spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true

This helps in debugging and understanding what Hibernate is doing under the hood.

38.What are derived properties?

Derived properties are not directly mapped to database columns. Instead, they are calculated based on expressions or SQL formulas at runtime.

Defined using formula attribute:

xml
<property name="totalSalary" formula="salary + bonus"/>

Usage:

  • Good for computed fields (e.g., full name, total cost, calculated age).

Note: These are read-only properties.


39 . Explain about transaction file?

Hibernate transactions manage the atomicity and consistency of database operations.

Key Points:

  • Started using session.beginTransaction().

  • Supports different transaction types: JDBC, JTA, CORBA.

  • Multiple operations (save, update, delete) can be performed inside a transaction.

Example:

java
Transaction tx = session.beginTransaction(); session.save(employee); session.update(address); tx.commit();

40 . Difference between session.save() , session.saveOrUpdate() and session.persist()?
Method Return Type Behavior
save() Serializable Inserts object. Fails if it is duplicate primary key.
saveOrUpdate() void Inserts or updates based on identifier.
persist() void Similar to save(), but follows JPA. Doesn’t return ID.

Key Differences:

  • save() returns ID.

  • persist() is strict — throws exceptions if entity is already persistent.

  • saveOrUpdate() is flexible.


41 . Explain about the id field?

The <id> element defines the primary key of the entity.

You can define:

  • Field name

  • Column mapping

  • Generation strategy (manual or automatic)

Example:

xml
<id name="id" column="EMP_ID"> <generator class="increment"/> </id>

Or annotation-based:

java
@Id @GeneratedValue(strategy = GenerationType.AUTO) private int id;
42.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
 dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
 dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

Used to optimize SQL generation.

Example:

xml
<class name="Product" dynamic-insert="true" dynamic-update="true">

Behavior:

  • dynamic-insert="true": INSERT only includes non-null fields.

  • dynamic-update="true": UPDATE only includes changed fields.


43.What is automatic dirty checking?

Hibernate automatically tracks object changes inside a session.

  • If a field is modified, Hibernate marks the object as "dirty".

  • During flush() or commit(), it updates only dirty fields in the DB.

No need for explicit update() call.


44.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

These interfaces or annotations allow you to hook into Hibernate’s lifecycle events.

Examples:

  • Lifecycle, Validatable

  • Annotations: @PostPersist, @PreRemove, @PostLoad, etc.

Use Cases:

  • Audit logging

  • Validation

  • Default value setting


45.What is Hibernate proxy?
 Hibernate uses proxies to implement lazy loading.
  • When you use session.load(), it returns a proxy object.

  • Actual DB hit happens when a method is called on that proxy.

  • Internally uses CGLIB or Javassist to generate the proxy class.

Benefit: Improves performance by deferring data load


46.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

To skip setter/getter and access field directly:

xml
<property name="name" access="field" />

Used in scenarios like legacy code or frameworks that require direct field manipulation.

47. What does "immutable" mean in Hibernate

 (or) How can a whole class be mapped as immutable in Hiberante?

🔷 What does "immutable" mean in Hibernate?

An immutable class in Hibernate is a class whose instances cannot be updated or deleted after being persisted into the database. Any change to an immutable entity will be ignored by Hibernate during flush or commit operations.

This is useful when dealing with reference or master data—data that never changes (like country codes, currency types, or predefined user roles).

Use mutable="false" in class mapping:

🔷 How to mark a class as immutable?

We can make a class immutable in Hibernate mapping (XML) using:

Using 1)xml

<class name="Country" table="COUNTRIES" mutable="false"> <id name="code" column="CODE" /> <property name="name" column="NAME" /> </class>

public class Country { private String code; private String name; // no-arg constructor required by Hibernate public Country() {} // getters and setters }

Country c = session.get(Country.class, "IN"); c.setName("India Updated"); // Hibernate will ignore this change during flush!
  • The attribute mutable="false" tells Hibernate not to track changes to this entity.

  • Any changes made to its fields will be ignored when flushing the session.

2)🔷 Use @Immutable Annotation

Hibernate provides @Immutable (from org.hibernate.annotations) to mark an entity as read-only — meaning:

  • Hibernate will never update or delete the object.

  • All change tracking (dirty checking) is disabled.

  • This is useful for read-only reference data like Country, Currency, etc.

🔷 Example: Marking a Class as Immutable

import javax.persistence.*;
import org.hibernate.annotations.Immutable; @Entity @Immutable @Table(name = "countries") public class Country { @Id private String code; private String name; // Required no-arg constructor public Country() {} // Getters public String getCode() { return code; } public String getName() { return name; } // Setters are optional (can omit if read-only) }

🔷 Behavior of @Immutable:

  • Hibernate will allow you to read the entity using session.get() or find().

  • But any changes to the fields will be ignored on flush() or commit().

  • If you call update() or delete() explicitly, Hibernate won’t perform SQL update/delete.

  • This helps protect data integrity of read-only tables.

🔷 Use Case Scenarios

ScenarioWhy use @Immutable?
Lookup tablesPrevent accidental update to countries, roles
Master/reference data     Where records are inserted once and never modified
Performance optimization Skips dirty-checking overhead
48 . Transparent Persistence in POJOs
 Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched.

Hibernate allows POJOs (Plain Old Java Objects) to be persisted without any base class or interface.

POJO Requirements:

  • No-arg constructor

  • Getter/setters

  • equals() and hashCode() implemented

  • Serializable (optional but recommended)


49 . What is the effect when a transient mapped object is passed onto a Sessions save?
If you pass a transient object (not yet associated with Hibernate session) to session.save():
  • It becomes persistent.

  • Hibernate assigns a primary key and schedules an INSERT operation.

  • Will remain in memory and tracked until explicitly removed or session is closed.


50 . Explain about addClass function?

Used in Hibernate configuration to map entities programmatically.

Example:

Configuration cfg = new Configuration();
cfg.addClass(Employee.class);
  • Internally, it looks for Employee.hbm.xml.

  • You can also use addResource("Employee.hbm.xml").

No comments:

Post a Comment