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
SessionFactory
?Session
instances.hibernate.cfg.xml
) to connect to the database.Session
?Transactions ensure data consistency. If an error occurs in the middle of an operation, the changes should be rolled back.
beginTransaction()
→ Starts a new transactioncommit()
→ Saves changes to the databaserollback()
→ Reverts changes if an error occursAn entity is a Java class that is mapped to a database table using annotations or XML mappings.
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 |
A dialect helps Hibernate translate HQL (Hibernate Query Language) into SQL for the specific database.
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 |
hibernate.cfg.xml