In this article i have explain the Create ,Update ,Read and Delete operation in ProductInfo table using JSF and Java Persistence API.
Step 1. Create The ProductInfo table in mysql database.
create table ProductInfo(
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(200),
shortDescription varchar(250),
longDescription varchar(500),
price double,
discount float,
categoryId int(11),
primary key(id)
);
Folder Structure of Project as
Step 2. Creating Entity class
ProductInfo.java
package entitiesClasses;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author brij
*/
@Entity
@Table(name = "productInfo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ProductInfo.findAll", query = "SELECT p FROM ProductInfo p"),
@NamedQuery(name = "ProductInfo.findById", query = "SELECT p FROM ProductInfo p WHERE p.id = :id"),
@NamedQuery(name = "ProductInfo.findByTitle", query = "SELECT p FROM ProductInfo p WHERE p.title = :title"),
@NamedQuery(name = "ProductInfo.findByPrice", query = "SELECT p FROM ProductInfo p WHERE p.price = :price"),
@NamedQuery(name = "ProductInfo.findByDiscount", query = "SELECT p FROM ProductInfo p WHERE p.discount = :discount"),
@NamedQuery(name = "ProductInfo.findByCategoryId", query = "SELECT p FROM ProductInfo p WHERE p.categoryId = :categoryId")})
public class ProductInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 200)
@Column(name = "title")
private String title;
@Lob
@Size(max = 65535)
@Column(name = "shortDescription")
private String shortDescription;
@Lob
@Size(max = 65535)
@Column(name = "longDescription")
private String longDescription;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "price")
private Double price;
@Column(name = "discount")
private Float discount;
@Column(name = "categoryId")
private Integer categoryId;
public ProductInfo() {
}
public ProductInfo(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Float getDiscount() {
return discount;
}
public void setDiscount(Float discount) {
this.discount = discount;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ProductInfo)) {
return false;
}
ProductInfo other = (ProductInfo) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "DataObject.ProductInfo[ id=" + id + " ]";
}
}
Step 3. Now Creating the EJB Model Classes
AbstractFacade.java
package ejbModel;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author brij
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
AbstractFacade.java contain the create ,update read and delete mathod .
ProductInfoFacade.java
package ejbModel;
import entitiesClasses.ProductInfo;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author brij
*/
@Stateless
public class ProductInfoFacade extends AbstractFacade<ProductInfo> {
@PersistenceContext(unitName = "jpaShopingPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ProductInfoFacade() {
super(ProductInfo.class);
}
}
Step 4. Now creating the Javabeans
ProductBean.java
package jpaShopingBean;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
/**
*
* @author brij
*/
@Named(value="productBean")
@SessionScoped
public class ProductBean implements Serializable{
private Integer id;
private String title;
private String shortDescription;
private String longDescription;
private Double price;
private Float discount;
private Integer categoryId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Float getDiscount() {
return discount;
}
public void setDiscount(Float discount) {
this.discount = discount;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
ProductBean.java has the product fields ,propertices and getter and setter of these fields .
now create the another class productController that control the our functionality
productController.java
package jpaShopingBean;
import entitiesClasses.ProductInfo;
import ejbModel.ProductInfoFacade;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* @author brij
*/
@Named(value="productController")
@SessionScoped
public class productController implements Serializable{
@EJB
ProductInfoFacade productInfoFacade;
@Inject
ProductBean productbean;
public List<ProductInfo> getAll() {
return productInfoFacade.findAll();
}
public int getCount() {
return productInfoFacade.count();
}
public String delete(ProductInfo p) {
productInfoFacade.remove(p);
return null;
}
public String addProduct() {
ProductInfo p=new ProductInfo();
p.setTitle(productbean.getTitle());
p.setShortDescription(productbean.getShortDescription());
p.setLongDescription(productbean.getLongDescription());
p.setPrice(productbean.getPrice());
p.setDiscount(productbean.getDiscount());
p.setCategoryId(productbean.getCategoryId());
productInfoFacade.create(p);
return "index";
}
public String editProduct(ProductInfo p) {
productbean.setId(p.getId());
productbean.setTitle(p.getTitle());
productbean.setShortDescription(p.getShortDescription());
productbean.setLongDescription(p.getLongDescription());
productbean.setPrice(p.getPrice());
productbean.setDiscount(p.getDiscount());
productbean.setCategoryId(p.getCategoryId());
return "updateProduct";
}
public String saveProduct() {
ProductInfo p=new ProductInfo();
p.setId(productbean.getId());
p.setTitle(productbean.getTitle());
p.setShortDescription(productbean.getShortDescription());
p.setLongDescription(productbean.getLongDescription());
p.setPrice(productbean.getPrice());
p.setDiscount(productbean.getDiscount());
p.setCategoryId(productbean.getCategoryId());
productInfoFacade.edit(p);
return "index";
}
}
Step 5. Now creating the JSF pages for performing CURD operation.
//for display the list of the product
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Product Info</title>
</h:head>
<h:body>
<h3>Total No of Product #{productController.getCount()}</h3>
<h:form>
<h:dataTable value="#{productController.getAll()}" var="product">
<h:column>
<f:facet name="header">
edit
</f:facet>
<h:commandLink value="Edit" action="#{productController.editProduct(product)}"/>
</h:column>
<h:column>
<f:facet name="header">ID</f:facet>
#{product.id}
</h:column>
<h:column>
<f:facet name="header">Title</f:facet>
#{product.title}
</h:column>
<h:column>
<f:facet name="header">Short Description</f:facet>
#{product.shortDescription}
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
#{product.price}
</h:column>
<h:column>
<f:facet name="header">Discount</f:facet>
#{product.discount}
</h:column>
<h:column>
<h:commandLink value="Delete" action="#{productController.delete(product)}"/>
</h:column>
</h:dataTable>
<h:commandButton value="Add New Product" action="addProduct">
</h:commandButton>
</h:form>
</h:body>
</html>
creating another jsf page addProduct.xhtml for adding the new product.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Add Product</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
Title
<h:inputText value="#{productBean.title}"></h:inputText>
Shot Description
<h:inputText value="#{productBean.shortDescription}"></h:inputText>
Long Description
<h:inputText value="#{productBean.longDescription}"></h:inputText>
Price
<h:inputText value="#{productBean.price}"></h:inputText>
Discount
<h:inputText value="#{productBean.discount}"></h:inputText>
Category Id
<h:inputText value="#{productBean.categoryId}"></h:inputText>
</h:panelGrid>
<h:commandButton value="Save" action="#{productController.addProduct()}"/>
</h:form>
</h:body>
</html>
creating another jsf page updateProduct.xhtml for adding the updating existing product.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Update Product</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
ID
<h:outputText value="#{productBean.id}"></h:outputText>
Title
<h:inputText value="#{productBean.title}"></h:inputText>
Short Description
<h:inputText value="#{productBean.shortDescription}"></h:inputText>>
Long Description
<h:inputText value="#{productBean.longDescription}"></h:inputText>
Price
<h:inputText value="#{productBean.price}"></h:inputText>
Discount
<h:inputText value="#{productBean.discount}"></h:inputText>
Category Id
<h:inputText value="#{productBean.categoryId}"></h:inputText>
</h:panelGrid>
<h:commandButton value="Save" action="#{productController.saveProduct()}"/>
</h:form>
</h:body>
</html>
Step 6. creating the glassfish-resource.xml file for configuring database setting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false"
connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0"
connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false"
is-isolation-level-guaranteed="true"
lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false"
max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000"
name="mysql_brij_shoppingcart_rootPool" non-transactional-connections="false"
pool-resize-quantity="2" res-type="javax.sql.DataSource"
statement-timeout-in-seconds="-1" steady-pool-size="8"
validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="brij_shoppingcart"/>
<property name="User" value="root"/>
<property name="Password" value=""/>
<property name="URL" value="jdbc:mysql://localhost:3306/brij_shoppingcart?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="java:app/jpaShoping" object-type="user" pool-name="mysql_brij_shoppingcart_rootPool"/>
</resources>
Step 7. Deploy and run the project .
List of the product
Add new product
Edit existing product