22.3 Example of managing book table through web application
Let’s take an example of managing book table through web application. Web application will have a feature of add a new book and display available books.
22.3.1 Design-
a) Design Book Entity
package com.tutorial.hibernate.entity; public class Book { private int id; private String isbn; private String name; private String author; private String publisher; private int price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
b. Create Book Table- Use the below create script to create book table.
CREATE TABLE ‘book’ ( ‘id’ int(11) NOT NULL AUTO_INCREMENT, ‘isbn’ varchar(255) DEFAULT NULL, ‘name’ varchar(255) DEFAULT NULL, ‘author’ varchar(255) DEFAULT NULL, ‘publisher’ varchar(255) DEFAULT NULL, ‘price’ int(11) DEFAULT NULL, PRIMARY KEY (‘id’); )
c. Hibernate.cfg.xml – Create a hibernate.cfg.xml file under src directory of web application.
jdbc:mysql://localhost:3306/tutorial root password org.hibernate.dialect.MySQLDialect true com.mysql.jdbc.Driver
d. book-mapping.hbm.xml – Create a book-mapping.hbm.xml file under src directory of web application.
This class contains the employee detail.
e. Create Servlets – We will create two servlets – one to insert the book data and another to retrieve all available book’s data.
GetDataServlet
package com.tutorial.hibernate.servlets; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.util.HibernateUtils; @WebServlet(“/GetDataServlet”) public class GetDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.openSession(); Query query = session.createQuery(“from Book”); List
books = query.list(); session.flush(); session.close(); request.setAttribute(“books”, books); request.getRequestDispatcher(“booksDetails.jsp”).forward(request, response); } }
InsertBookServlet
package com.tutorial.hibernate.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.util.HibernateUtils; @WebServlet(“/InsertBookServlet”) public class InsertBookServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String isbn = request.getParameter(“isbn”); String name = request.getParameter(“name”); String author = request.getParameter(“author”); String publisher = request.getParameter(“publisher”); String price = request.getParameter(“price”); Book book = new Book(); book.setAuthor(author); book.setIsbn(isbn); book.setName(name); book.setPrice(Integer.parseInt(price)); book.setPublisher(publisher); SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); session.save(book); session.flush(); tx.commit(); session.close(); response.sendRedirect(“GetDataServlet”); } }
f. Create JSP files – We will create three JSP files, home page (index.jsp) , insert books screen(insertBook.jsp) and display books details (bookDetails.jsp).
index.jsp
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>
Manage Books
Manage Books
insertBook.jsp
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>
Manage Books
<%@ page import=”java.util.List,com.tutorial.hibernate.entity.*” %>Insert Book
Enter Books Details
bookDetails.jsp
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>
Manage Books
<%@ page import=”java.util.List,com.tutorial.hibernate.entity.*” %>Available Books Details
<% List
books = (List
)request.getAttribute(“books”); %>Total Number of Books are <%= books.size() %>
ID ISBN NAME AUTHOR PUBLISHER PRICE <% for(int i=0;i
<%= book.getId() %> <%= book.getIsbn() %> <%= book.getName() %> <%= book.getAuthor() %> <%= book.getPublisher() %> <%= book.getPrice() %> <% } %>
g. Deploy and Run the web application by accessing http://localhost:8080/ManageDatabase
Below will be home page (index,jsp)
Click on InsertBook link and it will display insertBooks.jsp
Add books details and click save
This will save the book details in database and will display the book table data. We can click on Get Books link (available on home screen) also to see the books.
You can verify that data is stored in table. Refer below table state
Modifying the Hibernate Configuration File
When you create a new project that uses the Hibernate framework, the IDE automatically creates the
hibernate.cfg.xml
configuration file at the root of the context classpath of the application (in the Files window,
src/java
). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.
In this exercise you will edit the default properties specified in
hibernate.cfg.xml
to enable debug logging for SQL statements and to enable Hibernate’s session context management.
-
Open
hibernate.cfg.xml
in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking
hibernate.cfg.xml
. -
In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.
-
Click Add to open the Add Hibernate Property dialog box.
-
In the dialog box, select the
hibernate.show_sql
property and set the value to
true
. This enables the debug logging of the SQL statements.
-
Expand the Miscellaneous Properties node and click Add.
-
In the dialog box, select the
properties hibernate.current_session_context_class
and set the value to
thread
to enable Hibernate’s automatic session context management.
-
Click Add again under the Miscellaneous Properties node and select
hibernate.query.factory_class
in the Property Name dropdown list. -
Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.
If you click the XML tab in the editor you can see the file in XML view. Your file should look similar to the following (the three new properties are bold):
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### *true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *
-
Save your changes to the file.
You can close the file because you do not need to edit the file again.
List of Users
Edit
Delete