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.
- update =update the schema in accordance with our entity class.
- create=generates the schema, discarding previous data.
- validate=validate the schema, but make no changes to the database.
- create-drop=When the SessionFactory is explicitly closed, i.e. when the application is stopped, the schema is dropped.
- none=None means that no changes are made to the schema or the database.
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 }
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; } }
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(); } }
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"); } }
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
0 Comments
If you have any doubts let me know.