Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Saturday, February 3, 2018

CURD(Create,Update,Read,Delete) In JSF Using Java Persistence API


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


   
   

Entities In Java Persistence API

Entities In Java Persistence :

An entities is a lightweight persistence domain object.Typically an entity represents a table in relational database, and each entity instance corresponds to a row in that tables.

The persistent state of an entity is represented either through persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.


Requirements for Entity Classes:-


An entity class must follow these requirements:
1.The class must be annotated with the javax.persistence.Entity annotation.
2.The class must have a public or protected ,no-argument constructor. The class may have other constructors.
3.The class must not be declared final. No method or persistent instance variable must be declared final.
4.Entities may extend both entity and non-entity classes,and non-entity classes may extend entity classes.
5.Persistent instance variables must be declared private, protected, or package-private, and can only be accessed directly by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.
   
 
Persistent Fields and Properties in Entity Classes:- 

The persistent state of an entity can be accessed either through the entity's   instance variable or through JavaBeans-style properties. The fields or properties must be the following java language types:

 1. Java primitive types.
 2. Java.lang.String.

 Other serializable types including:-
 
  * Wrappers of java primitive types.
  * Java.math.BigInteger
  * Java.math.BigDecimal
  * Java.util.Date
  * Java.util.Calendar
  * Java.sql.Date
  * Java.sql.Time
  * Java.sql.TimeStamp
 
 User-defined serializable types:-

 
  *byte[]
  *Bytes[]
  *char[]
  *character[]

Enumerated types
Other entities and collections of entities.
Embeddable classes

Entities may either use persistent fields or persistent properties. If the mapping annotations are applied to the entity’s instance variables,
the entity uses persistent fields.

Persistent Fields:-


If the entity class uses persistent fields, the Persistence runtime accesses entity class instance variables directly.
all fields not annotated javax.persistence.Transient or not marked as java transient will be persisted to data store. The Object/relation mapping annotation
must be applied to the instance variables.


Persistent Properties:-

If the entity class use persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter
methods that are typically named after the entity class's instance variable names. For every persistent property property of type Type of the entity, there is a getter method getProperty and setter method setProperty.

The method signature for single -valued persistent properties as follow:-

Type getProperty()
void setProperty(Type type)

Collection-valued persistent fields and properties must use the supported Java collection interfaces regardless of whether the entity uses persistent fields or properties.
The following collection interfaces may be used:

  *java.util.Collection
  *java.util.Set
  *java.util.List
  *java.util.Map
 
Primary Keys in Entities:-
 
Each object has a unique identifier. A customer entity, for example , might be identified by a customer number.
The unique identifier, or primary key, enables clients to locate a particular entity instance.
Every entity must have a primary key. An entity may have either a simple or a composite primary key.

The primary key, or the property or field of a composite primary key, must be one of the following Java language types:

    Java primitive types

    Java primitive wrapper types

    java.lang.String

    java.util.Date (the temporal type should be DATE)

    java.sql.Date

Floating point types should never be used in primary keys. If you use a generated primary key, only integral types will be portable.

Primary Key Clasees:-

A primary key class must these requirements:
  *The access control modifier of the class must be public.
  *The properties of the primary key class must be public or protected if property based access is used.
  *The class must have a public default constructor.
  *The class must be serializable

Multiplicity in Entity Relationships:-


 There are four types of multiplicities :
  1. one-to-one
  2. one-to-many
  3. many-to-one
  4. many-to-many

1. One-To-One:- Each entity instance is related to a single instance of another entity. For example, to model a physical warehouse in which each storage bin conatins a single widget.
2. One-To-Many:- An entity instance can be related to multiple instance of the other entities. A sales order, for example,can have multiple line items. In the order application,order would have a one-to-many relationship with line item.
3. Many-To-one:- Multiple instance of an entity can be related to a single instance of the other entity. this Multiplicity is the opposite of a one-to-many relationship.
4. Many-To-Many:-The antity instance can be related to multiple instance of each other. For example, in college each course has many students ,a nd every may take several courses.therefore in an enrollment application, Course and Student would have a many-to-many relationship.

Entity Inheritence:-
 
 Entities support class inheritence, polymorphic associations, and polymorphic queries. They can extend non-entity classes, and non-entity classes can extend entity classes. ENtity classes can be both abstract and concrete.

Abstract Entities:-


 An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities differ from
 concrete entities only in that they cannot be instantiated.

 Abstract entities can be queried just like concrete queries. If an abstract entity is the target of a query, the query operates on all the concrete subclasses of the abstract entity.

@Entity
public abstract class Employee {
    @Id
    protected Integer employeeId;
    ...
}
@Entity
public class FullTimeEmployee extends Employee {
    protected Integer salary;
    ...
}
@Entity
public class PartTimeEmployee extends Employee {
    protected Float hourlyWage;
}



 

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...