JSP Servlet Hibernate CRUD Example

In this blog post, we will create a simple JSP, Servlet, and Hibernate-based application to perform CRUD (Create, Read, Update, Delete) operations on a Book entity using Hibernate 6.4 and a MySQL database.

Overview of the Technologies

JSP (JavaServer Pages)

  • Role: Presentation Layer
  • Function: Allows embedding of Java code directly within HTML to create dynamic content.
  • Benefits: Simplifies the development of web pages with dynamic content.

Servlets

  • Role: Controller Layer
  • Function: Handles HTTP requests and responses, connecting the presentation layer to the business logic.
  • Benefits: Provides a robust and scalable way to handle user requests and server responses.

Hibernate

  • Role: Persistence Layer
  • Function: A powerful ORM (Object-Relational Mapping) tool that facilitates interaction with the database.
  • Benefits: Simplifies database operations, improving development speed, maintainability, and portability.

MVC Pattern

In this example, we will follow the Model-View-Controller (MVC) pattern to organize the codebase:

  • Model: Represents the data and the rules of the application. In Java, this is usually a POJO (Plain Old Java Object) annotated to interact with a database using Hibernate.
  • View: The end-user interface, typically handled by JSP files that generate the HTML sent to the user's browser.
  • Controller: Processes user input from the View, updates the Model, and returns the output display to the user.

Step-by-Step Tutorial

Step 1: Create a Dynamic Web Project

  1. Open Eclipse and go to File > New > Project....
  2. Select Web > Dynamic Web Project and click Next.
  3. Name the project jsp-servlet-hibernate-mysql-example.
  4. Set the target runtime to Apache Tomcat.
  5. Click Finish.

Step 2: Add Dependencies

Add the following dependencies to your pom.xml file if using Maven, or download the JAR files and add them to the lib folder:

<dependencies>
    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.0.Final</version>
    </dependency>
    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.32</version>
    </dependency>
    <!-- Jakarta Persistence API -->
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.0.0</version>
    </dependency>
    <!-- JSP and Servlets -->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>5.0.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jakarta.servlet.jsp</groupId>
        <artifactId>jakarta.servlet.jsp-api</artifactId>
        <version>3.0.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSTL -->
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jakarta.servlet.jsp.jstl</artifactId>
        <version>2.0.0</version>
    </dependency>
</dependencies>

Step 3: MySQL Database Setup

Create a database named demo in MySQL and a books table using the following SQL script:

CREATE DATABASE demo;
USE demo;

CREATE TABLE books (
    id INT NOT NULL AUTO_INCREMENT,
    title VARCHAR(120) NOT NULL,
    author VARCHAR(120) NOT NULL,
    price DOUBLE,
    PRIMARY KEY (id)
);

Step 4: Create Book Entity

Create a Book entity class:

package com.example.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

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

    @Column(name = "price")
    private double price;

    // Constructors, getters, setters, and toString() method
    public Book() {}

    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    // Getters and setters omitted for brevity
}

Step 5: Configure Hibernate

Create HibernateUtil class to bootstrap Hibernate:

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;

import com.example.entity.Book;

import java.util.Properties;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();
                Properties settings = new Properties();
                settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
                settings.put(Environment.URL, "jdbc:mysql://localhost:3306/demo?useSSL=false");
                settings.put(Environment.USER, "root");
                settings.put(Environment.PASS, "root");
                settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL8Dialect");
                settings.put(Environment.SHOW_SQL, "true");
                settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
                settings.put(Environment.HBM2DDL_AUTO, "update");

                configuration.setProperties(settings);
                configuration.addAnnotatedClass(Book.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();

                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }

    public static void shutdown() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }
}

Step 6: Create DAO Class for CRUD Operations

Create BookDao class to handle CRUD operations:

package com.example.dao;

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

import java.util.List;

public class BookDao {

    public void saveBook(Book book) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(book);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public List<Book> getBooks() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery("FROM Book", Book.class).list();
        }
    }

    public void updateBook(Book book) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.update(book);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void deleteBook(Long bookId) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            Book book = session.get(Book.class, bookId);
            if (book != null) {
                session.delete(book);
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public Book getBook(Long bookId) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.get(Book.class, bookId);
        }
    }
}

Step 7: Create Servlets for CRUD Operations

Create servlets to handle HTTP requests for CRUD operations.

AddBookServlet

package com.example.servlet;

import com.example.dao.BookDao;
import com.example.entity.Book;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {

    private BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("add-book.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        double price = Double.parseDouble(req.getParameter("price"));

        Book book = new Book(title, author, price);
        bookDao.saveBook(book);

        resp.sendRedirect("listBooks");
    }
}

ListBooksServlet

package com.example.servlet;

import com.example.dao.BookDao;
import com.example.entity.Book;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/listBooks")
public class ListBooksServlet extends HttpServlet {

    private BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Book> books = bookDao.getBooks();
        req.setAttribute("books", books);
        req.getRequestDispatcher("list-books.jsp").forward(req, resp);
    }
}

UpdateBookServlet

package com.example.servlet;

import com.example.dao.BookDao;
import com.example.entity.Book;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/updateBook")
public class UpdateBookServlet extends HttpServlet {

    private BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Long id = Long.parseLong(req.getParameter("id"));
        Book book = bookDao.getBook(id);
        req.setAttribute("book", book);
        req.getRequestDispatcher("update-book.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Long id = Long.parseLong(req.getParameter("id"));
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        double price = Double.parseDouble(req.getParameter("price"));

        Book book = new Book(id, title, author, price);
        bookDao.updateBook(book);

        resp.sendRedirect("listBooks");
    }
}

DeleteBookServlet

package com.example.servlet;

import com.example.dao.BookDao;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/deleteBook")
public class DeleteBookServlet extends HttpServlet {

    private BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Long id = Long.parseLong(req.getParameter("id"));
        bookDao.deleteBook(id);
        resp.sendRedirect("listBooks");
    }
}

Step 8: Create JSP Pages

add-book.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Add Book</title>
</head>
<body>
    <h2>Add Book</h2>
    <form action="addBook" method="post">
        Title: <input type="text" name="title" required><br>
        Author: <input type="text" name="author" required><br>
        Price: <input type="text" name="price" required><br>
        <input type="submit" value="Add Book">
    </form>
    <a href="listBooks">View Books</a>
</body>
</html>

list-books.jsp

<!DOCTYPE html>
<html>
<head>
    <title>List Books</title>
</head>
<body>
    <h2>List of Books</h2>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Author</th>
            <th>Price</th>
            <th>Actions</th>
        </tr>
        <c:forEach var="book" items="${books}">
            <tr>
                <td>${book.id}</td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.price}</td>
                <td>
                    <a href="updateBook?id=${book.id}">Edit</a>
                    <a href="deleteBook?id=${book.id}">Delete</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <a href="addBook">Add New Book</a>
</body>
</html>

update-book.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Update Book</title>
</head>
<body>
    <h2>Update Book</h2>
    <form action="updateBook" method="post">
        <input type="hidden" name="id" value="${book.id}">
        Title: <input type="text" name="title" value="${book.title}" required><br>
        Author: <input type="text" name="author" value="${book.author}" required><br>
        Price: <input type="text" name="price" value="${book.price}" required><br>
        <input type="submit" value="Update Book">
    </form>
    <a href="listBooks">View Books</a>
</body>
</html>

Step 9: Configure Servlet Annotations

Using servlet annotations, there is no need to configure web.xml. The servlet classes are annotated with @WebServlet.

Step 10: Run the Application

Deploy the application on a Tomcat server and access the application through your browser. You can perform CRUD operations on the Book entity through the provided JSP pages.

Summary

This tutorial provided a comprehensive step-by-step guide to setting up a JSP and Servlet-based application with Hibernate 6.4, configuring it with a MySQL database, creating a Book entity, and performing CRUD operations using servlets and JSP pages. By following these steps, you can effectively manage and manipulate database records in a web application using Hibernate and JSP/Servlets.

Related Servlet Posts

Comments

  1. hey bro i need help the project run good but when i add new user the data doesn't insert into database

    ReplyDelete
  2. Hi,
    I followed the tutorial but I am getting this error as
    "The import org.hibernate cannot be
    resolved". Please help me

    ReplyDelete
    Replies
    1. u make sure that "added" hibernate in lib

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi Bro,
    How to auto-genrate create table schema instead of manually create in mysql terminal

    ReplyDelete
  5. i aways get an error.

    ```org.hibernate.property.access.spi.PropertyAccessException: Error accessing field```

    when i opt the data

    ReplyDelete
  6. Hi sir, thanks for the great tutorial.
    I added a servlet for login and from my loginServlet i try to access the "UserServlet"
    but i keep getting an error when trying to add a new user or update it. the problem is with my action because it returns /UserServlet instead of /new or /list. Can you please help me solve this issue I tried multiple ways but nothing works.

    ReplyDelete

Post a Comment

Leave Comment