Practical-8C:JPA Application to store and retrieve Book Details
/*MySQl Code*/
mysql> create database bookdb;
mysql> use bookdb;
mysql>create table booktb(isbn int(3) PRIMARY KEY auto_increment,
bookname char(20),bookprice int(3),bookqty int(3));
/*index.jsp*/
<%@page contentType="text/html" pageEncoding="UTF-8"%>
JSP Page
Enter Book Details
/*Book.java*/
package myApp;
import javax.persistence.*;
@Entity
@Table(name="booktb")
public class Book
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="isbn",unique=true,updatable=false)
Integer isbn;
@Column(name="bookname")
String bookname;
@Column(name="bookprice")
String bookprice;
@Column(name="bookqty")
String bookqty;
public Book(){}
public Book(Integer isbn)
{
this.isbn=isbn;
}
public String getBookname()
{
return bookname;
}
public void setBookname(String bookname)
{
this.bookname=bookname;
}
public String getBookprice()
{
return bookprice;
}
public void setBookprice(String bookprice)
{
this.bookprice=bookprice;
}
public String getBookqty()
{
return bookqty;
}
public void setBookqty(String bookqty)
{
this.bookqty=bookqty;
}
public Integer gstisbn()
{
return isbn;
}
public void setItemid(Integer isbn)
{
this.isbn=isbn;
}
}
/*BookView.jsp*/
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.List,
java.util.Iterator,myApp.Book,javax.persistence.*"%>
<%!
EntityManagerFactory emf;
EntityManager em;
EntityTransaction tx;
Listbook;
%>
<%
emf=Persistence.createEntityManagerFactory("WebApplication8CPU");
em=emf.createEntityManager();
String submit=request.getParameter("btnsubmit");
if(submit!=null&&("Submit").equals(submit))
{
try
{
String name=request.getParameter("bname");
String price=request.getParameter("bprice");
String qty=request.getParameter("bqty");
Book gb=new Book();
gb.setBookname(name);
gb.setBookprice(price);
gb.setBookqty(qty);
tx=em.getTransaction();
tx.begin();
em.persist(gb);
tx.commit();
}
catch(Exception e)
{
if(tx!=null)
tx.rollback();
throw e;
}
response.sendRedirect("BookView.jsp");
}
try
{
book=em.createQuery("select g from Book g").getResultList();
}
catch(Exception e)
{
throw e;
}
em.close();
%>
JSP Page
View the Book List
Click here to go back
<%
Iterator it=book.iterator();
while(it.hasNext())
{
Book obj=(Book)it.next();
%>
<%=obj.getBookname()%>
<%=obj.getBookprice()%>
<%=obj.getBookqty()%>
<%
}
%>