Open In App

How to Download and Install Hibernate ORM?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Hibernate ORM (Object-Relational Mapping) is a powerful tool for mapping Java objects to database tables, making database access in Java applications much easier. It abstracts the complexities of database interactions, allowing developers to focus on business logic. This article will walk you through downloading, installing, and configuring Hibernate ORM in a Java project.

Prerequisites:

Before starting, ensure you have the following:

  • Java Development Kit (JDK): Hibernate 6.x requires JDK 11 or later. Download from Oracle’s official website or use OpenJDK.
  • Integrated Development Environment (IDE): You should have an IDE like Eclipse or IntelliJ IDEA.
  • Maven or Gradle: These build tools help manage Hibernate dependencies.

Step-by-Step Implementation

Step 1: Download Hibernate ORM

You can either download Hibernate manually or add it via Maven or Gradle (recommended).

Manual Download:

  1. Visit the official Hibernate ORM website.
  2. Open the "Downloads" section.
  3. Download the latest stable version of Hibernate ORM.
  4. Extract the ZIP file to access the JAR files and documentation.

While manual download is possible, it is better to use a build tool like Maven or Gradle to manage dependencies, which simplifies future updates.

Hibernate-ORM

Step 2: Set Up Hibernate ORM with Maven

Maven simplifies dependency management. It automatically downloads necessary libraries and handles updates.

  • Create a Maven Project: In your IDE, create a new Maven project.
  • Add Dependencies: Open the pom.xml file and add Hibernate and database dependencies.

XML:

<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.5.Final</version>
</dependency>

<!-- MySQL or other database dependency -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.34</version>
</dependency>
</dependencies>
  • Update Maven Project: After adding the dependencies, update your Maven project to download the required libraries.

Step 3: Configure Hibernate ORM with Gradle

If you’re using Gradle, adding Hibernate is equally simple:

  • Create a Gradle Project: In your IDE, create a new Gradle project.
  • Add Dependencies: Open the build.gradle file and add the Hibernate and MySQL dependencies.

Groovy:

dependencies {
implementation 'org.hibernate.orm:hibernate-core:6.2.5.Final'
implementation 'mysql:mysql-connector-java:8.0.34'
}
  • Sync Project: Sync your Gradle project to automatically download the required libraries.

Step 4: Configure Hibernate ORM

Once Hibernate ORM is added to your project, you need to configure it to connect to your database. This can be done using an XML configuration file (hibernate.cfg.xml) or programmatically. Here’s the XML approach:

Create hibernate.cfg.xml: In the src/main/resources directory, create a file named hibernate.cfg.xml.

Example Configuration for MySQL:

<!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/yourdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>

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

<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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>

<!-- Automatically update the database schema -->
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mention your annotated classes -->
<mapping class="com.example.YourEntity"/>
</session-factory>
</hibernate-configuration>

This file configures Hibernate to connect to a MySQL database with connection pooling, logs SQL commands, and automatically updates the database schema.

Important Note: In production environments, never store database credentials directly in the configuration file. Use environment variables or a secure configuration management system.

The hibernate.hbm2ddl.auto property can have the following values:

  • validate: Validates the schema but makes no changes
  • update: Updates the schema if necessary
  • create: Creates the schema, destroying previous data
  • create-drop: Creates the schema and drops it when the SessionFactory closes Choose the appropriate option based on your development or production needs.

Step 5: Create an Entity Class

Hibernate uses entity classes to map Java objects to database tables. You need to annotate your Java classes to make them recognizable by Hibernate.

Here’s an example of an entity class:

Java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employees")
public class Employee {
    
    @Id
    private int id;
    private String name;
    private String department;
    
    // Getters and Setters
}

In this example, the Employee class is mapped to a table named employees, and its fields are mapped to the corresponding columns in the table.

Step 6: Write a Hibernate Example

Finally, let’s write a simple example to demonstrate how to save an object into the database using Hibernate.

Java
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        
        Employee employee = new Employee();
        employee.setId(1);
        employee.setName("John Doe");
        employee.setDepartment("IT");
        
        session.save(employee);
        transaction.commit();
        session.close();
    }
}

In this example, we use Hibernate to open a session, create a transaction, save an Employee object, and commit the transaction.

Conclusion

Hibernate ORM simplifies database interactions in Java by automating the mapping between Java objects and database tables. You have now learned how to download, install, and configure Hibernate ORM using Maven or Gradle, as well as how to set up a simple entity and save it to the database. Hibernate is a robust solution for simplifying database access in Java applications due to its flexibility and ease of use.


Next Article

Similar Reads