Hello everyone,

Greetings today!

Today we will use maven to create a web application and perform crud operations. As a controller, we will use a servlet to handle all incoming requests. If you don't know what a servlet is or how it works,  read my post.

What Is Servlet In Java? Servlet With Example + Servlet Lifecycle

So let's get started.

Open eclipse & Go to File -New -other and search for maven, then click on maven project.

 

Then select maven-archetype-webapp by clicking next.

Then, as shown below, enter the group id and artifact id and click finish.

We now have a basic project structure in place.

Now, in MySQL, create the table Books, which will be used in this application.

create database test_db;

CREATE  TABLE `test_db`.`Books` (
  `BOOK_ID` INT NOT NULL AUTO_INCREMENT ,
  `BOOK_TITLE` VARCHAR(45) NOT NULL ,
  `BOOK_PRICE` VARCHAR(45) NOT NULL ,
  `BOOK_AUTHOR` VARCHAR(45) NOT NULL ,
   PRIMARY KEY (`BOOK_ID`) 
);

Now open pom.xml and add MySQL, JSTL, hibernate-core, and log4j as dependencies.

Now we'll go to src/main/resources and create the file hibernate.cfg.xml to configure database-related properties in our application.

Note-replace username & password with your DB credentials.

Here hibernate.hbm2ddl.auto has the following possible values.

  1. update =update the schema in accordance with our entity class.
  2. create=generates the schema, discarding previous data.
  3. validate=validate the schema, but make no changes to the database.
  4. create-drop=When the SessionFactory is explicitly closed, i.e. when the application is stopped, the schema is dropped.
  5. none=None means that no changes are made to the schema or the database.

Also, show_sql when set to true will print the corresponding native SQL query during DB operations.

Now, create a model class Book.java in which we will specify a table name, column name, and so on.
package com.demo.book.model;

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

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

 @Id
 @Column(name="BOOK_ID")
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private long bookId;
	
 @Column(name = "BOOK_TITLE")
 private String bookTitle;

 @Column(name = "BOOK_PRICE")
 private BigDecimal bookPrice;

 @Column(name = "BOOK_AUTHOR")
 private String bookAuthor;

 public Book(long bookId, String bookTitle, BigDecimal bookPrice, 
 	String bookAuthor) {
   
   super();
   this.bookId = bookId;
   this.bookTitle = bookTitle;
   this.bookPrice = bookPrice;
   this.bookAuthor = bookAuthor;
  }

  public Book() {
  }
  
  //TODO GENERATE GETTERS AND SETTERS
}
Now we will add code to get SessionFactory, which will load hibernate.cfg.xml to obtain the session factory.

We are using the singleton design pattern to create an instance of SessionFactory, which means that the instance is created only once when the getSessionFactory() method is called, and all subsequent calls to getSessionFactory() will return the same instance.

So, as shown below, create Book.util.java.
package com.demo.book.util;

public class BookUtil {
	
  private static SessionFactory sessionFactory;
	
  public static SessionFactory getSessionFactory() {
   
   if(sessionFactory==null) {
	  
    Configuration configuration=new Configuration();
	configuration.configure("hibernate.cfg.xml");
	
    ServiceRegistry serviceRegistry 
      = new StandardServiceRegistryBuilder()
      .applySettings(configuration.getProperties()).build();
			 
   configuration.addAnnotatedClass(Book.class);	 
   
   sessionFactory=configuration
    	.buildSessionFactory(serviceRegistry);		 
  }
  
  return sessionFactory;
 }	
}
Let's now create a repository layer for the various crud methods such as create, read, update, and delete.

So create BookDAO.java
package com.demo.book.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.demo.book.model.Book;
import com.demo.book.util.BookUtil;

public class BookDAO {

  public void addUpdateBook(Book book) {

   SessionFactory sessionFactory = BookUtil.getSessionFactory();
   Session session = sessionFactory.openSession();
   Transaction transaction = session.beginTransaction();
   session.saveOrUpdate(book);
   transaction.commit();
   session.close();
 }

 public List<Book> findAllBooks() {
   SessionFactory sessionFactory = BookUtil.getSessionFactory();
   Session session = sessionFactory.openSession();
   return session
   	.createQuery("from Book", Book.class).getResultList();
 }

 public Book findBookByBookId(long bookId) {
   SessionFactory sessionFactory = BookUtil.getSessionFactory();
   Session session = sessionFactory.openSession();
   return session.find(Book.class, bookId);
 }

 public void deleteBookById(long bookId) {
   Book book = findBookByBookId(bookId);
   SessionFactory sessionFactory = BookUtil.getSessionFactory();
   Session session = sessionFactory.openSession();
   Transaction transaction = session.beginTransaction();
   session.delete(book);
   transaction.commit();
   session.close();
 }
}
Note that we are using the saveOrUpdate method, so if the record is not available, it will be created, and if it already exists, it will be updated rather than created.

We will now create the add book.jsp file in src/main/webapp. We use the same form for add and edit, and if a user edits the book, we need to show data that the user previously saved.

In the controller, we will retrieve previous data and place it in the request attribute, as shown below, which will then be displayed using JSTL.

request.setAttribute("book", book);
                

Now, under src/main/webapp, create view_books.jsp, where we will add code to display books that we have stored, as well as links to edit and delete books.

We will fetch data in the controller and store it in the request attribute, which will be used to render data in view_books.jsp using JSTL.

Now we must create a servlet that will serve as a controller for incoming requests. To create a servlet, right-click on the package, i.e. com.demo.book.controller, select new-other, search for a servlet, enter BookController as the class name, and click Finish.


We are handling all CRUD requests here, and after each operation, we are redirecting the user back to view books.jsp using the request Dispatcher's forward method.
We use BookDAO methods for CRUD operations.

package com.demo.book.controller;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.demo.book.dao.BookDAO;
import com.demo.book.model.Book;

/**
 * Servlet implementation class BookController
 */
public class BookController extends HttpServlet {

  private static final Logger LOGGER 
    = Logger.getLogger(BookController.class);

  public BookController() {
	super();
  }

  protected void doGet
   (HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
  {
  String flag = request.getParameter("flag");
  handleRequestUsingFlag(request, response, flag);
  }

  private void handleRequestUsingFlag
    	(HttpServletRequest request, 
        HttpServletResponse response, String flag)
	throws ServletException, IOException 
 {

  BookDAO bookDAO = new BookDAO();

  if ("editBook".equalsIgnoreCase(flag)) {
   
   long bookId = Long.valueOf(request.getParameter("bookId"));
   Book book = bookDAO.findBookByBookId(bookId);
   
   request.setAttribute("book", book);
   request.getRequestDispatcher("add_book.jsp")
    .forward(request, response);
  
  }else if ("deleteBook".equalsIgnoreCase(flag)) {
   
   String bookId = request.getParameter("bookId");
   bookDAO.deleteBookById(Long.valueOf(bookId)); 
     
   List<Book> books = bookDAO.findAllBooks();
	request.setAttribute("books", books);
	request.getRequestDispatcher("view_books.jsp")
      	.forward(request, response);
 }else {
   List<Book> books = bookDAO.findAllBooks();
   request.setAttribute("books", books);
   request.getRequestDispatcher("view_books.jsp")
      	.forward(request, response);
 }
}

protected void doPost(HttpServletRequest request,
	HttpServletResponse response)
	throws ServletException, IOException {
	
  BookDAO bookDAO = new BookDAO();

  BigDecimal bookPrice = new BigDecimal
   (request.getParameter("bookPrice"));
	
  String bookTitle = request.getParameter("bookTitle");
  String bookAuthor = request.getParameter("bookAuthor");
  String bookId = request.getParameter("bookId");

  Book book = new Book();
  book.setBookAuthor(bookAuthor);
  book.setBookPrice(bookPrice);
  book.setBookTitle(bookTitle);
  if (bookId != "" && Long.valueOf(bookId) > 0) {
    book.setBookId(Long.valueOf(bookId));
  }

  bookDAO.addUpdateBook(book);
  handleRequestUsingFlag(request, response, "viewBooks");
 }
}
Simply add a link to add_book.jsp and view_books.jsp from the index.jsp now.
Now that we've finished our development, right-click on the index.jsp and select run on a server (You need to have tomcat configured in eclipse).

O/P


The project structure is shown below for reference.

Let me know if you have any questions.

Thanks

Enjoy your learning!


You can also refer to the post below.

Spring Boot JDBC Template CRUD Operation

Named Query In Hibernate & JPA + @NamedNativeQuery + @NamedQuery

Spring Boot REST API Export To Excel Using Apache POI

Spring Boot CRUD With PostgreSQL And Spring REST + Spring JPA

Spring Rest API + CRUD Example + Spring Boot + Oracle Database + Spring JPA 

Spring MVC CRUD + Spring Boot + Oracle + Thymeleaf

Java JDBC CRUD Example + Using JSP & Servlet + MySQL

For all java & java, 8 tutorial refer below page