In this session, we will walk through the setup and configuration of Hibernate using annotations for a PostgreSQL database. This will include setting up the project, configuring Hibernate, and performing CRUD operations.
Prerequisites:
- Java 8+ installed on your machine.
- PostgreSQL installed and running on your system.
- Maven or Gradle for dependency management.
- IDE like IntelliJ IDEA or Eclipse.
1. Set Up Project
Add Dependencies to pom.xml
Ensure that the necessary dependencies are added to your pom.xml
file for Hibernate, PostgreSQL, and JPA.
2. Hibernate Configuration File (hibernate.cfg.xml
)
Create the hibernate.cfg.xml
file in the src/main/resources
directory. This file contains the Hibernate configuration settings.
Explanation:
hibernate.dialect
: Specifies the dialect for PostgreSQL (PostgreSQLDialect
).hibernate.url
: The JDBC URL for connecting to PostgreSQL (jdbc:postgresql://localhost:5432/hibernate_example
).hibernate.username
andhibernate.password
: Database connection credentials.hibernate.hbm2ddl.auto
: Specifies how Hibernate handles schema generation (update
for automatic updates).hibernate.show_sql
: Enables the logging of executed SQL queries.
3. Create Entity Class (Employee
)
The entity class will represent the table in the PostgreSQL database. Let's define an Employee
entity class using Hibernate annotations.
Annotations Used:
@Entity
: Marks this class as a Hibernate entity.@Table
: Specifies the table in the database (employee
).@Id
: Marks the primary key of the entity.@GeneratedValue
: Indicates the auto-generation strategy for the primary key (GenerationType.IDENTITY
is used for auto-increment).@Column
: Specifies the mapping between the entity field and the table column.
4. Hibernate Utility Class
This utility class will provide the SessionFactory
and manage the session lifecycle.
Explanation:
- The
SessionFactory
is configured using thehibernate.cfg.xml
file. - The
addAnnotatedClass
method registers theEmployee
entity. getSessionFactory()
returns theSessionFactory
, andshutdown()
closes it when the application ends.
5. Main Application to Perform CRUD Operations
Now, let's implement the main class to perform CRUD operations on the Employee
table.
Explanation of CRUD Operations:
- Create: An
Employee
instance is created and persisted usingsession.save()
. - Read: The employee is retrieved by ID using
session.get()
. - Update: The employee's salary is updated using
session.update()
. - Delete: The employee is deleted using
session.delete()
.
Comments
Post a Comment