Step 1: Create a Maven Project
1. Open Eclipse and go to File > New > Project....
2. Select Web > Maven Project and click Next.
3. Name the project 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.