Introduction
Hibernate is an Object-Relational Mapping (ORM) framework that simplifies database interactions in Java applications. By mapping Java classes to database tables, Hibernate allows developers to interact with databases using standard Java objects, reducing the need for manual SQL queries.
In this tutorial, we will:
- Set up a Maven project with Hibernate and Oracle dependencies.
- Configure Hibernate to connect to an Oracle database.
- Create an entity class that maps to a database table.
- Implement basic CRUD operations using Hibernate.
- Write a main method to perform these CRUD operations and print sample output.
Step 1: Set Up Your Project
1.1 Create a Maven Project
Open your IDE and create a new Maven project.
1.2 Add Dependencies
Update your pom.xml
file to include the necessary dependencies for Hibernate and Oracle.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>hibernate-oracle-tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.0.Final</version>
</dependency>
<!-- Oracle JDBC Driver -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.8.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.3 Configure Hibernate
Create a file named hibernate.cfg.xml
in the src/main/resources
directory to configure Hibernate.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
Replace orcl
with your Oracle service name, and username
and password
with your Oracle database credentials.
Step 2: Create the Entity Class
Create an entity class User
that will be mapped to a table in the database.
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Step 3: Create the Hibernate Utility Class
Create a utility class HibernateUtil
to manage the Hibernate SessionFactory
.
package com.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Step 4: Perform CRUD Operations
4.1 Create a User
package com.example.main;
import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CreateUser {
public static void createUser() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
User user = new User();
user.setName("Ramesh Fadatare");
user.setEmail("ramesh.fadatare@example.com");
session.save(user);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
}
4.2 Read a User
package com.example.main;
import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
public class ReadUser {
public static void readUser(Long userId) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
User user = session.get(User.class, userId);
if (user != null) {
System.out.println("User details: " + user.getName() + ", " + user.getEmail());
} else {
System.out.println("User not found!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
}
4.3 Update a User
package com.example.main;
import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class UpdateUser {
public static void updateUser(Long userId, String newName, String newEmail) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
User user = session.get(User.class, userId);
if (user != null) {
transaction = session.beginTransaction();
user.setName(newName);
user.setEmail(newEmail);
session.update(user);
transaction.commit();
} else {
System.out.println("User not found!");
}
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
}
4.4 Delete a User
package com.example.main;
import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class DeleteUser {
public static void deleteUser(Long userId) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
User user = session.get(User.class, userId);
if (user != null) {
transaction = session.beginTransaction();
session.delete(user);
transaction.commit();
} else {
System.out.println("User not found!");
}
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
}
Step 5: Write the Main Method to Call CRUD Operations
package com.example.main;
public class MainApp {
public static void main(String[] args) {
// Create a new user
CreateUser.createUser();
System.out.println("User created!");
// Read the created user
ReadUser.readUser(1L);
// Update the created user
UpdateUser.updateUser(1L, "Ramesh Updated", "ramesh.updated@example.com");
System.out.println("User updated!");
// Read the updated user
ReadUser.readUser(1L);
// Delete the user
DeleteUser.deleteUser(1L);
System.out.println("User deleted!");
// Try to read the deleted user
ReadUser.readUser(1L);
}
}
Sample Output
User created!
User details: Ramesh Fadatare, ramesh.fadatare@example.com
User updated!
User details: Ramesh Updated, ramesh.updated@example.com
User deleted!
User not found!
Conclusion
In this tutorial, we have successfully set up a Hibernate project using Hibernate 6.4, Oracle, and Java 21. We created an entity class and configured Hibernate to connect to an Oracle database. We performed basic CRUD operations (Create, Read, Update, Delete) to demonstrate how to interact with the database using Hibernate. This guide provides a solid foundation for building more complex Hibernate-based applications.
Comments
Post a Comment
Leave Comment