Hibernate MS SQL Server Database Tutorial

This tutorial will guide you through setting up Hibernate with an MS SQL Server database and Java 21, creating a simple application that demonstrates basic CRUD operations using a Book entity. 

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:

  1. Set up a Maven project with Hibernate and MS SQL Server dependencies.
  2. Configure Hibernate to connect to an MS SQL Server database.
  3. Create an entity class (Book) that maps to a database table.
  4. Implement basic CRUD operations using Hibernate.
  5. 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 MS SQL Server.

<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-mssql-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>

        <!-- MS SQL Server Connector -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>10.2.1.jre17</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.SQLServerDialect</property>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=hibernate_db</property>
        <property name="hibernate.connection.username">sa</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 hibernate_db with your database name, and sa and password with your MS SQL Server credentials.

Step 2: Create the Entity Class

Create an entity class Book 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 Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private Double price;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

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 Book

package com.example.main;

import com.example.entity.Book;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CreateBook {
    public static void createBook() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Book book = new Book();
            book.setTitle("Effective Java");
            book.setAuthor("Joshua Bloch");
            book.setPrice(45.0);
            session.save(book);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.2 Read a Book

package com.example.main;

import com.example.entity.Book;
import com.example.util.HibernateUtil;
import org.hibernate.Session;

public class ReadBook {
    public static void readBook(Long bookId) {
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            Book book = session.get(Book.class, bookId);
            if (book != null) {
                System.out.println("Book details: " + book.getTitle() + ", " + book.getAuthor() + ", " + book.getPrice());
            } else {
                System.out.println("Book not found!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.3 Update a Book

package com.example.main;

import com.example.entity.Book;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UpdateBook {
    public static void updateBook(Long bookId, String newTitle, String newAuthor, Double newPrice) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            Book book = session.get(Book.class, bookId);
            if (book != null) {
                transaction = session.beginTransaction();
                book.setTitle(newTitle);
                book.setAuthor(newAuthor);
                book.setPrice(newPrice);
                session.update(book);
                transaction.commit();
            } else {
                System.out.println("Book not found!");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.4 Delete a Book

package com.example.main;

import com.example.entity.Book;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DeleteBook {
    public static void deleteBook(Long bookId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            Book book = session.get(Book.class, bookId);
            if (book != null) {
                transaction = session.beginTransaction();
                session.delete(book);
                transaction.commit();
            } else {
                System.out.println("Book 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 book
        CreateBook.createBook();
        System.out.println("Book created!");

        // Read the created book




        ReadBook.readBook(1L);

        // Update the created book
        UpdateBook.updateBook(1L, "Effective Java 3rd Edition", "Joshua Bloch", 50.0);
        System.out.println("Book updated!");

        // Read the updated book
        ReadBook.readBook(1L);

        // Delete the book
        DeleteBook.deleteBook(1L);
        System.out.println("Book deleted!");

        // Try to read the deleted book
        ReadBook.readBook(1L);
    }
}

Sample Output

Book created!
Book details: Effective Java, Joshua Bloch, 45.0
Book updated!
Book details: Effective Java 3rd Edition, Joshua Bloch, 50.0
Book deleted!
Book not found!

Conclusion

In this tutorial, we have successfully set up a Hibernate project using Hibernate 6.4, MS SQL Server, and Java 21. We created an entity class and configured Hibernate to connect to an MS SQL Server 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