Hibernate Example using XML in Eclipse (original) (raw)

Hibernate is an ORM (Object-Relational Mapping) framework that simplifies database interactions in Java by handling most of the underlying JDBC work automatically. It allows developers to focus on business logic instead of writing complex SQL queries and managing connections manually.

Prerequisites

Step To Configuring a Hibernate using XML in Eclipse

Follow these steps to set up and configure a Hibernate application in Eclipse, including project creation, dependency setup, configuration files, and execution.

Step 1: Create Maven Project in Eclipse

Follow these steps to create a project in Eclipse:

1. Open Eclipse IDE
2. Click on File ->New -> Maven Project
3. Select Create a simple project (skip archetype selection) -> Click Next
4. Enter project details:

5. Click Finish

Step 2: Add Dependencies (Hibernate + MySQL)

Add Hibernate and MySQL dependencies so the project can connect to the database.

XML `

org.hibernate.orm hibernate-core 6.2.7.Final
<!-- MySQL Connector (Stable) -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

<!-- JPA API (Required with Hibernate 6) -->
<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>3.1.0</version>
</dependency>

`

Step 3: Create Database

CREATE DATABASE geeksforgeeks;

Step 4: Create POJO Class (Model)

Create a Java class that represents the database table structure.

Java `

import java.util.Date;

public class GeekUserDetails { private int geekUserId; private String geekUsername; private int numberOfPosts; private String createdBy; private Date createdDate;

public int getGeekUserId() { return geekUserId; }
public void setGeekUserId(int geekUserId)
{
    this.geekUserId = geekUserId;
}

public String getGeekUsername() { return geekUsername; }
public void setGeekUsername(String geekUsername)
{
    this.geekUsername = geekUsername;
}

public int getNumberOfPosts() { return numberOfPosts; }
public void setNumberOfPosts(int numberOfPosts)
{
    this.numberOfPosts = numberOfPosts;
}

public String getCreatedBy() { return createdBy; }
public void setCreatedBy(String createdBy)
{
    this.createdBy = createdBy;
}

public Date getCreatedDate() { return createdDate; }
public void setCreatedDate(Date createdDate)
{
    this.createdDate = createdDate;
}

}

`

**Explanation: This is a Java POJO (Plain Old Java Object) class that represents a database entity with fields and getter/setter methods to store and access user details.

Step 5: Create Mapping File (geekuser.hbm.xml)

Map Java class fields with database table columns.

XML `

    <id name="geekUserId" column="geekUserId" type="int">
        <generator class="assigned"/>
    </id>

    <property name="geekUsername" column="geekUsername"/>
    <property name="numberOfPosts" column="numberOfPosts"/>
    <property name="createdBy" column="CREATED_BY"/>
    <property name="createdDate" column="CREATED_DATE"/>

</class>

`

**Explanation: This Hibernate mapping file defines how the GeekUserDetails Java class is mapped to the database table and its columns.

Step 6: Create Hibernate Configuration File (hibernate.cfg.xml)

Configure database connection and auto table creation here.

XML `

    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/geeksforgeeks</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">YOUR_PASSWORD</property>

    <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

    <!-- Auto table creation -->
    <property name="hibernate.hbm2ddl.auto">update</property>

    <property name="hibernate.show_sql">true</property>

    <mapping resource="geekuser.hbm.xml"/>
</session-factory>

`

**Explanation: This Hibernate configuration file sets up database connection details, Hibernate properties, and links the mapping file to enable ORM functionality.

Step 7: Create Hibernate Utility Class

import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory
    = buildSessionFactory();

private static SessionFactory buildSessionFactory()
{
    try {
        return new Configuration()
            .configure()
            .buildSessionFactory();
    }
    catch (Throwable ex) {
        System.err.println(
            "SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory()
{
    return sessionFactory;
}

}

`

**Explanation: his utility class creates and provides a single reusable SessionFactory instance for managing Hibernate database connections.

Step 8: Create Main Class (Insert Data)

import java.util.Date; import org.hibernate.Session; import org.hibernate.Transaction;

public class GeekUserDetailsTest {

public static void main(String[] args)
{
    // Open session
    Session session = HibernateUtil.getSessionFactory()
                          .openSession();

    // Begin transaction
    Transaction tx = session.beginTransaction();

    // Create object
    GeekUserDetails geekUser = new GeekUserDetails();
    geekUser.setGeekUserId(1);
    geekUser.setGeekUsername("GeekUser1");
    geekUser.setNumberOfPosts(100);
    geekUser.setCreatedBy("GeekUser1");
    geekUser.setCreatedDate(new Date());

    // Save object
    session.save(geekUser);

    // Commit transaction
    tx.commit();

    // Close session
    session.close();
}

}

`

**Explanation: This class tests Hibernate by creating a GeekUser object, saving it to the database, and committing the transaction.

Step 9: Final Output

Data is inserted via hibernate session

**Video explanation about the code: