✅ 1. What is the Advantage of Hibernate over JDBC?
Hibernate offers several powerful advantages over traditional JDBC:
| # | Hibernate | JDBC |
|---|---|---|
| 1️⃣ | Database Independence | Hibernate abstracts DB-specific queries. Works across MySQL, Oracle, PostgreSQL, etc. |
| 2️⃣ | Object-Oriented Design | Treats tables as Java objects (POJOs). |
| 3️⃣ | No Need to Learn SQL | With HQL/Criteria API, most work is done in Java. |
| 4️⃣ | Automatic Query Optimization | Hibernate optimizes queries automatically via Criteria API. |
| 5️⃣ | Caching Support | Supports 1st and 2nd level cache for performance. |
| 6️⃣ | Faster Development | Less boilerplate code, faster CRUD development. |
| 7️⃣ | Connection Pooling Support | Supports C3P0, HikariCP, etc. |
| 8️⃣ | Mapping & Relations in XML/Annotations | Easier to visualize and maintain object relationships. |
| 9️⃣ | Lazy Loading Support | Load data on demand (lazy=false for eager). |
| 🔟 | Versioning and Optimistic Locking | Built-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?
| Level | Description |
|---|---|
| 1️⃣ Pure Relational | SQL and stored procedures only |
| 2️⃣ Light Object Mapping | JDBC with basic mapping to POJOs |
| 3️⃣ Medium Object Mapping | Some OOP concepts like inheritance |
| 4️⃣ Full Object Mapping | Full OOP support with relationships, inheritance, lazy loading, etc. — Hibernate lies here |
✅ 6. Why Use ORM Tools like Hibernate?
| Benefit | Explanation |
|---|---|
| 🔁 DB Independence | Write code once, use with any supported DB. |
| 💡 Productivity | Less boilerplate code, use HQL instead of SQL. |
| 🚀 Performance | Built-in caching, lazy/eager loading. |
| 🔄 Maintainability | Less coupling, easier to refactor. |
| 🌍 Portability | SQL 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)
| Feature | Hibernate | Entity Beans (EJB) |
|---|---|---|
| DB Support | Multiple DBs via config | Limited DB support |
| Container | No special container needed | Requires EJB container |
| OOP Support | Full support (inheritance, polymorphism) | Limited |
| Caching | Built-in multilevel cache | Not supported |
| Connection Pooling | Uses C3P0, Hikari, etc. | Manual setup |
| Portability | Lightweight & portable | Heavy, tied to container |
✅ 9. Core Interfaces and Classes in Hibernate
| Interface/Class | Purpose |
|---|---|
Configuration | Loads config file & mapping (hibernate.cfg.xml) |
SessionFactory | Singleton factory for sessions, created once per app |
Session | Main interface to interact with DB, represents unit of work |
Transaction | Used to begin, commit, or rollback transactions |
Query / Criteria | For fetching data via HQL, native SQL, or Criteria API |
✅ 10. Hibernate Execution Flow
-
Load Configuration
-
Build SessionFactory
-
Open Session
-
Begin Transaction
-
Perform Operation
-
Commit and Close
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:
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:
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:
14. What role does the SessionFactory interface play in Hibernate?
SessionFactory is a thread-safe, heavyweight object responsible for:
-
Creating
Sessioninstances -
Caching mappings, SQL, and metadata
-
Acting as a second-level cache provider
-
Created once per application (usually singleton)
Characteristics:
-
Immutable
-
Created using
Configurationobject -
Expensive to create
Example:
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.
4. Annotations:
From Hibernate 3.3 onwards, JPA annotations are supported directly in entity classes.
16. How do you map Java objects with DB tables?
Steps:
-
Create Java Bean (POJO with setters/getters)
-
Create mapping file (
*.hbm.xml) -
Define class-to-table and property-to-column mappings
Example:
17. How do you define sequence-generated primary key in Hibernate?
You use the <id> tag and <generator> subtag.
Example using Oracle/Postgres sequence:
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
@Embeddableand@Embeddedin annotations -
Requires a no-arg constructor
-
Shared references not supported
XML Example:
Annotation Example:
19. Difference between getCurrentSession() and openSession() in Hibernate?
| Feature | getCurrentSession() | openSession() |
|---|---|---|
| Session management | Managed by Hibernate (bound to transaction) | Manual (you must close it explicitly) |
| Auto close | Yes | No |
| Auto flush | Yes | No |
| Thread safe | Not safe across threads | Not safe across threads |
| Use case | Best in JTA or Spring transactions | Use when manual control is needed |
openSession():
Example with getCurrentSession():
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()
Hibernate supports three types of inheritance mapping strategies for mapping Java class hierarchies to database tables:
-
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.
-
-
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.
-
-
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.
-
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:
23. What are the ways to express joins in HQL?
HQL supports multiple ways to represent inner and outer joins:
-
Implicit Association Join
-
Automatically joins based on mapped relationships.
-
-
Explicit Join in FROM Clause
-
Manual join with optional
joinorleft join.
-
-
Fetch Join
-
Used to initialize associated entities eagerly.
-
-
Theta-Style Join (in WHERE clause)
-
Traditional SQL-style join using conditions.
-
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:
-
Begin transaction with
session.beginTransaction(). -
Perform DB operations.
-
Commit or rollback.
-
Always close the session.
Example:
Configuration:
25. Best Practices for Defining Hibernate Persistent Classes
-
Default Constructor
-
Required by Hibernate to instantiate objects via reflection.
-
-
Getter and Setter Methods
-
Hibernate uses these to read/write fields.
-
-
equals() and hashCode()
-
Use business keys (like email/SSN), not auto-generated IDs.
-
IDs might be null before saving to DB.
-
-
Serializable Interface
-
Enables caching, session replication in clusters.
-
-
Avoid Final Classes
-
Final classes prevent Hibernate from using proxies for lazy loading.
-
-
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
| Feature | Sorted Collection | Ordered Collection |
|---|---|---|
| Sorting Location | Java (in-memory) | Database |
| Mechanism | Java Comparator | SQL ORDER BY |
| Efficiency | Best for small collections | Best for large datasets |
| Annotation/Config | @SortComparator | @OrderBy |
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:
Invocation in Java:
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):
-
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:
No comments:
Post a Comment