Advertisement
Google Ad Slot: content-top
HB Core Concepts
Hibernate provides a powerful ORM (Object-Relational Mapping) framework that simplifies database interactions in Java applications. In this section, we'll explore the core components of Hibernate:
✅ Session & SessionFactory
✅ Transaction Management
✅ Entity Classes and Mappings
✅ Hibernate Dialects
Session & SessionFactory:
What is SessionFactory?
- A heavyweight object that creates
Sessioninstances. - It is thread-safe and should be created once per application.
- Uses a configuration file (
hibernate.cfg.xml) to connect to the database.
What is Session?
- A lightweight object used to interact with the database.
- It is not thread-safe and should be created per database operation.
- Used to perform CRUD (Create, Read, Update, Delete) operations.
Transaction Management
Why Use Transactions?
Transactions ensure data consistency. If an error occurs in the middle of an operation, the changes should be rolled back.
Transaction Methods
beginTransaction()→ Starts a new transactioncommit()→ Saves changes to the databaserollback()→ Reverts changes if an error occurs
Entity Classes and Mappings
What is an Entity?
An entity is a Java class that is mapped to a database table using annotations or XML mappings.
Common Hibernate Annotations
Annotation |
Description |
|---|---|
@Entity |
Marks the class as an Entity (Table in DB) |
@Table(name="table_name") |
Defines a custom table name |
@Id |
Marks a field as Primary Key |
@GeneratedValue(strategy = GenerationType.IDENTITY) |
Enables Auto-Increment for the ID |
@Column(name="column_name") |
Maps a field to a specific column name |
@Transient |
Prevents a field from being saved in the DB |
@Temporal(TemporalType.DATE) |
Stores Date-only values |
@OneToOne,@OneToMany,@ManyToOne,@ManyToMany |
Defines Relationships |
Example: Entity Class with Mappings:
Hibernate Dialects
What is a Hibernate Dialect?
A dialect helps Hibernate translate HQL (Hibernate Query Language) into SQL for the specific database.
Common Hibernate Dialects
Database |
Hibernate Dialect |
|---|---|
MySQL |
org.hibernate.dialect.MySQLDialect |
PostgreSQL |
org.hibernate.dialect.PostgreSQLDialect |
Oracle |
org.hibernate.dialect.OracleDialect |
SQL Server |
org.hibernate.dialect.SQLServerDialect |
H2 (In-Memory) |
org.hibernate.dialect.H2Dialect |