Home CRUD operations with Hibernate
Post
Cancel

CRUD operations with Hibernate

Hibernate Vs JPA:

In this blog post, we’ll explore how to perform CRUD (Create, Read, Update, Delete) operations using Hibernate, with examples.

CRUD operations with Hibernate

Before we start, let’s set up a basic Hibernate project. We’ll assume that you’re using Maven to manage dependencies.

1: Add the Hibernate dependencies to your Maven pom.xml file:

1
2
3
4
5
6
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.5.7.Final</version>
</dependency>

2: Create a Hibernate configuration using Java DSL (alternate we can use hibernate.cfg.xml )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/database_name");
            configuration.setProperty("hibernate.connection.username", "root");
            configuration.setProperty("hibernate.connection.password", "password");
            configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
            configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
            configuration.setProperty("hibernate.hbm2ddl.auto", "create");
            configuration.addAnnotatedClass(Student.class);
            return configuration.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

3: Create a Java class that represents a table in your database. This class should have private instance variables for each column in the table, along with getters and setters for each variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    // getters and setters
}

4: Perform CURD Operation

Create Operation

To perform a create operation using Hibernate, we first need to obtain a session object. We can use the session object to save a new object to the database.

1
2
3
4
5
6
7
8
9
10
11
12
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();

Student student = new Student();
student.setName("John");
student.setAge(21);

session.save(student);
transaction.commit();
session.close();

In the above example, we first obtain a session object using HibernateUtil.getSessionFactory().openSession(). We then create a new Student object, set its name and age, and save it to the database using session.save(student). We then commit the transaction and close the session.

Read Operation

To perform a read operation using Hibernate, we first need to obtain a session object. We can use the session object to load an object from the database by its ID.

1
2
3
4
5
6
7
8
9
Session session = HibernateUtil.getSessionFactory().openSession();

Student student = session.get(Student.class, 1L);

System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());

session.close();

In the above example, we first obtain a session object using HibernateUtil.getSessionFactory().openSession(). We then load a Student object from the database using session.get(Student.class, 1L), where 1L is the ID of the object we want to load. We then print the name and age of the object, and close the session.

Update Operation

To perform an update operation using Hibernate, we first need to obtain a session object. We can use the session object to load an object from the database, update its properties, and save it

1
2
3
4
5
6
7
8
9
10
11
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();

Student student = session.get(Student.class, 1L);
student.setName("Jane");
student.setAge(22);

session.update(student);
transaction.commit();
session.close();

In the above example, we first obtain a session object using HibernateUtil.getSessionFactory().openSession(). We then load a Student object from the database using session.get(Student.class, 1L), where 1L is the ID of the object we want to update. We then update the object’s name and age, and save the changes to the database using session.update(student). We then commit the transaction and close the session.

Delete Operation

To perform a delete operation using Hibernate, we first need to obtain a session object. We can use the session object to load an object from the database by its ID and delete it from the database.

1
2
3
4
5
6
7
8
9
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();

Student student = session.get(Student.class, 1L);

session.delete(student);
transaction.commit();
session.close();

In the above example, we first obtain a session object using HibernateUtil.getSessionFactory().openSession(). We then load a Student object from the database using session.get(Student.class, 1L), where 1L is the ID of the object we want to delete. We then delete the object from the database using session.delete(student). We then commit the transaction and close the session.

Conclusion

In this blog post, we explored how to perform CRUD operations using Hibernate, with examples. We saw how to set up a basic Hibernate project, and how to use the session object to save, load, update, and delete objects from the database. Hibernate is a powerful ORM framework that simplifies database access for Java applications. By following the examples in this blog post, you can get started with Hibernate and start building robust Java applications that interact with a database.

This post is licensed under CC BY 4.0 by the author.