Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

Hibernate Example using XML in Eclipse

Using Hibernate with XML-based configuration is a traditional method, which was commonly used before the adoption of annotations and JPA. Here's a step-by-step guide to setting up a basic Hibernate project with XML-based configuration in Eclipse:

1. Create a New Java Project

  1. Open Eclipse IDE.
  2. Go to File > New > Java Project.
  3. Enter a project name and click Finish.

2. Add Required JARs

For Hibernate to work, you'll need certain JARs:

  1. Download the Hibernate ORM framework from the official website.
  2. Extract the downloaded zip file.
  3. Right-click on your project in Eclipse, then go to Properties > Java Build Path > Libraries.
  4. Click on Add External JARs and add the required Hibernate and JPA jars from the extracted folder.
  5. Also, add the MySQL JDBC driver (you can download it separately).

3. Hibernate Configuration (XML)

Create a hibernate.cfg.xml file in the src directory:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database_name</property>
        <property name="hibernate.connection.username">your_username</property>
        <property name="hibernate.connection.password">your_password</property>

        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">5000</property>

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

        <!-- Enable Hibernate's automatic session context management -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <!-- Mention annotated class-->
        <mapping resource="com/example/Book.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

4. Create Entity and Mapping XML

Book.java (POJO):

package com.example;

public class Book {
    private int id;
    private String title;
    private String author;

    // Getters, Setters, Constructors...
}

Book.hbm.xml (Hibernate Mapping):

Create an XML file named Book.hbm.xml:

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.example.Book" table="book">
        <id name="id" type="int" column="id">
            <generator class="native"/>
        </id>
        <property name="title" column="title" type="string"/>
        <property name="author" column="author" type="string"/>
    </class>
</hibernate-mapping>

5. CRUD Operations

Use a SessionFactory to perform CRUD operations:

package com.example;

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

public class BookManager {
    private static SessionFactory sessionFactory;

    public static void main(String[] args) {
        sessionFactory = new Configuration().configure().buildSessionFactory();
        
        BookManager manager = new BookManager();
        Book book = new Book("Hibernate in Action", "Christian Bauer");
        manager.addBook(book);

        sessionFactory.close();
    }

    private int addBook(Book book) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        int id = (Integer) session.save(book);

        session.getTransaction().commit();
        session.close();

        return id;
    }

    // Implement other CRUD operations similarly
}

6. Run the Application

When you run the BookManager class, Hibernate will create the book table in your MySQL database and insert a new entry. Remember, this is a very basic example; in real-world scenarios, you'd handle exceptions, possibly use a DAO pattern, and manage resources more effectively.

  1. Configuring Hibernate with XML in Eclipse:

    • Description: Configure Hibernate in Eclipse by creating the hibernate.cfg.xml file. This file includes database connection details, dialect, and other Hibernate settings.
    • Code:
      <!-- hibernate.cfg.xml -->
      <hibernate-configuration>
          <session-factory>
              <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
              <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
              <property name="hibernate.connection.username">your_username</property>
              <property name="hibernate.connection.password">your_password</property>
              <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
              <!-- other properties -->
          </session-factory>
      </hibernate-configuration>
      
  2. Creating Hibernate entities using XML in Eclipse:

    • Description: Define Hibernate entities using XML mapping files (hbm.xml). Each entity corresponds to a database table, and properties are mapped to columns.
    • Code:
      <!-- Employee.hbm.xml -->
      <hibernate-mapping>
          <class name="com.example.Employee" table="employee">
              <id name="id" type="long">
                  <generator class="native"/>
              </id>
              <property name="firstName" type="string"/>
              <property name="lastName" type="string"/>
              <!-- other properties -->
          </class>
      </hibernate-mapping>
      
  3. Hibernate XML mapping for associations in Eclipse:

    • Description: Define associations between entities using XML mapping files. Use <set>, <many-to-one>, <one-to-many>, etc., to represent associations.
    • Code:
      <!-- Department.hbm.xml -->
      <hibernate-mapping>
          <class name="com.example.Department" table="department">
              <id name="id" type="long">
                  <generator class="native"/>
              </id>
              <property name="name" type="string"/>
              <set name="employees" table="employee" inverse="true" lazy="true">
                  <key>
                      <column name="department_id"/>
                  </key>
                  <one-to-many class="com.example.Employee"/>
              </set>
          </class>
      </hibernate-mapping>
      
  4. Mapping inheritance using XML in Hibernate Eclipse project:

    • Description: Use XML mapping files to represent inheritance strategies in Hibernate. <subclass>, <joined-subclass>, and <union-subclass> elements are used for various inheritance mappings.
    • Code:
      <!-- Person.hbm.xml -->
      <hibernate-mapping>
          <class name="com.example.Person" table="person">
              <id name="id" type="long">
                  <generator class="native"/>
              </id>
              <property name="name" type="string"/>
              <!-- other properties -->
          </class>
      </hibernate-mapping>
      
      <!-- Employee.hbm.xml -->
      <hibernate-mapping>
          <subclass name="com.example.Employee" extends="com.example.Person" discriminator-value="employee">
              <property name="salary" type="double"/>
              <!-- other properties specific to Employee -->
          </subclass>
      </hibernate-mapping>