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 [Link] file if using Maven, or
download the JAR files and add them to the lib folder:
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<!-- Jakarta Persistence API -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- JSP and Servlets -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]</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 [Link];
import [Link].*;
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = [Link])
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) {
[Link] = title;
[Link] = author;
[Link] = price;
}
// Getters and setters omitted for brevity
}
Step 5: Configure Hibernate
Create HibernateUtil class to bootstrap Hibernate:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
[Link]([Link], "[Link]");
[Link]([Link],
"jdbc:mysql://localhost:3306/demo?useSSL=false");
[Link]([Link], "root");
[Link]([Link], "root");
[Link]([Link],
"[Link].MySQL8Dialect");
[Link](Environment.SHOW_SQL, "true");
[Link](Environment.CURRENT_SESSION_CONTEXT_CLASS,
"thread");
[Link](Environment.HBM2DDL_AUTO, "update");
[Link](settings);
[Link]([Link]);
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder()
.applySettings([Link]()).build();
sessionFactory =
[Link](serviceRegistry);
} catch (Exception e) {
[Link]();
}
}
return sessionFactory;
}
public static void shutdown() {
if (sessionFactory != null) {
[Link]();
}
}
}
Step 6: Create DAO Class for CRUD Operations
Create BookDao class to handle CRUD operations:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class BookDao {
public void saveBook(Book book) {
Transaction transaction = null;
try (Session session =
[Link]().openSession()) {
transaction = [Link]();
[Link](book);
[Link]();
} catch (Exception e) {
if (transaction != null) {
[Link]();
}
[Link]();
}
}
public List<Book> getBooks() {
try (Session session =
[Link]().openSession()) {
return [Link]("FROM Book", [Link]).list();
}
}
public void updateBook(Book book) {
Transaction transaction = null;
try (Session session =
[Link]().openSession()) {
transaction = [Link]();
[Link](book);
[Link]();
} catch (Exception e) {
if (transaction != null) {
[Link]();
}
[Link]();
}
}
public void deleteBook(Long bookId) {
Transaction transaction = null;
try (Session session =
[Link]().openSession()) {
transaction = [Link]();
Book book = [Link]([Link], bookId);
if (book != null) {
[Link](book);
}
[Link]();
} catch (Exception e) {
if (transaction != null) {
[Link]();
}
[Link]();
}
}
public Book getBook(Long bookId) {
try (Session session =
[Link]().openSession()) {
return [Link]([Link], bookId);
}
}
}
Step 7: Create Servlets for CRUD Operations
Create servlets to handle HTTP requests for CRUD operations.
AddBookServlet
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {
private BookDao bookDao = new BookDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("[Link]").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String title = [Link]("title");
String author = [Link]("author");
double price = [Link]([Link]("price"));
Book book = new Book(title, author, price);
[Link](book);
[Link]("listBooks");
}
}
ListBooksServlet
package [Link];
import [Link];
import [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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 = [Link]();
[Link]("books", books);
[Link]("[Link]").forward(req, resp);
}
}
UpdateBookServlet
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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 = [Link]([Link]("id"));
Book book = [Link](id);
[Link]("book", book);
[Link]("[Link]").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Long id = [Link]([Link]("id"));
String title = [Link]("title");
String author = [Link]("author");
double price = [Link]([Link]("price"));
Book book = new Book(id, title, author, price);
[Link](book);
[Link]("listBooks");
}
}
DeleteBookServlet
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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 = [Link]([Link]("id"));
[Link](id);
[Link]("listBooks");
}
}
Step 8: Create JSP Pages
[Link]
<!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>
[Link]
<!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>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>
<a href="updateBook?id=${[Link]}">Edit</a>
<a href="deleteBook?id=${[Link]}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
<a href="addBook">Add New Book</a>
</body>
</html>
[Link]
<!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="${[Link]}">
Title: <input type="text" name="title" value="${[Link]}"
required><br>
Author: <input type="text" name="author" value="${[Link]}"
required><br>
Price: <input type="text" name="price" value="${[Link]}"
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 [Link]. 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.