Hibernate and Primefaces CRUD Using NetBeans 8.02 and MySQL Database Server

Introduction 

 
This simple application is a Create, Read, Update and Delete application operating on a ‘User’ table in ‘test’ database in MySQL Database Server. It is a Hibernate-Annotation based application.
 
Software Used
  1. JDK8u25
  2. Netbeans 8.02
  3. MySQL 5.*(or XAMPP)
  4. MySQL Connector 5.*
  5. Hibernate 4.3.** and Primefaces 5.0(Bundled with Netbeans)
Steps
  1. Install JDK8 or Jdk7 if not installed
  2. Install Netbeans and associated ApacheTomcat Server
  3. Install MySQL Database server or XAMPP(For easy management of MySQL ) .
After Installing Netbeans click the services tab on the left. Expand Database node. Expand Drivers node. Right click MySQL(Connector/Jdriver) then connect. Put test as the database, as shown below. Put password if you have given your password at the time of installation of MySQL database server. For XAMPP no password is required. Then test connection. If successful click finish button.
 
 
 
Create user table by running the below SQL in ‘test’ database.
  1. CREATE TABLE IF NOT EXISTS `user` (  
  2.     `id` int(10) unsigned NOT NULL auto_increment,  
  3.     `RecordNo` varchar(20) DEFAULT NULL,  
  4.     `Name` varchar(50) DEFAULT NULL,  
  5.     `Age` int(11) DEFAULT NULL,  
  6.     `Sex` varchar(20) DEFAULT NULL,  
  7.     `Dob` date DEFAULT NULL,  
  8.     `Remark` varchar(50) DEFAULT NULL PRIMARY KEY(`id`)  
  9. ) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;  
Insert these Records below by executing the below insert statement:
  1. INSERT INTO `user` (`id`, `RecordNo`, `Name`, `Age`, `Sex`, `Dob`, `Remark`) VALUES  
  2. (1, '1''Raichand', 48, 'Male''2014-06-16''Good Person'),  
  3. (2, '2''Ramesh', 45, 'Male''2013-03-18''Good Person'),  
  4. (3, '3''smita', 47, 'Female''1996-01-09''Jolly Lady'),  
  5. (4, '4''Sarita', 37, 'Female''1998-01-07''good beautiful lady'),  
  6. (7, '7''Rashmi', 23, 'Male''2016-01-25''good person'),  
  7. (9, '9''Deepak', 21, 'Male''2016-01-26''good person'),  
  8. (10, '10''Jyoti Rath', 21, 'Male''2016-01-26''good person'),  
  9. (11, '11''Sruti Rath', 21, 'Male''2016-01-26''good person'),  
  10. (13, '13''Pradipta Prusty', 34, 'Male''2016-01-18''good person'),  
  11. (14, '14''sunita misra', 21, 'Female''2016-01-27''good lady'),  
  12. (15, '15''sibananda mitra', 32, 'Male''2016-01-25''good person'),  
  13. (16, '16''smita rath', 23, 'Female''2016-01-20''good lady'),  
  14. (17, '17''Smita satpathy', 21, 'Female''2016-01-26''good lady'),  
  15. (18, '18''N.C Das', 32, 'Male''2016-01-26''Good Person'),  
  16. (26, '19''sarita subudhi', 43, 'Female''2016-01-26''good lady'),  
  17. (27, '27''Ravi Mohanty', 44, 'Male''2016-01-26''good person'),  
  18. (28, '28''Sita', 23, 'Female''2016-02-23''good lady');  
Creating Project UserCRUD_Annotation
 
File->New Project->Categories->Choose JavaWeb->Choose WebApplication->Click Next->Give Project Name UserCRUD_Annotation->Click Next->Click Next->Choose Framework First Hibernate then Java Server Faces->Click Component Tab->Choose Primefaces->Click Finish.
 
 
 
Download mysql- connector-java-bin.jar and add to libraries folder by copying and pasting.
 
Project Structure
 
 
 
Creating Packages and Classes
 
Right click Source Package folder and create four packages: 
  1. com.controller.bean: This would contain JSF Managed Bean Class UsererBean.java.
  2. com.dao: This would contain DAO(Data Access Object) class UsererDao.java.
  3. com.model.pojo: This would contain entity(POJO) class User.java.POJO Stands for Plain Old Java. Objects
  4. com.util: This will contain HibernateUtil.java class.
Default package contains two files hibernate.cfg.xml and hibernate.reveng.xml file:
 
Following Files would be created using Netbeans:
  1. hibernate.cfg,xml File: Automatically generated.
  2. Reverse Engineering File: hibernate.reveng.xml
  3. Entity(POJO) File: User.java(POJO stands for Plain Old Java Objects)
  4. JSF Managed Bean File: UserBean.java
  5. DataAccessObject(DAO) File: UserDao.java
  6. HibernateUtil.java File
  7. Index.xhtml(Automatically generated): Adds new user and displays all users information
  8. Search.xhtml: Search a user then edit or delete it
  9. UserCrud.xhtml: It is an independent file to be run independently by selecting it in TOC and running it by Run(From Menu): Run File
  10. web.xml(Automatically generated)
Add mysql- connector-java-bin.jar to libraries folder by copy and paste if not done.
 
Copy and paste code of the file given below whose code is not generated
 
1. Hibernate.cfg.xml File
 
As XAMPP is used so there is no password in the file only username is given that is root in Hibernate.cfg.xml File.
 
Code
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  3. <hibernate-configuration>  
  4.     <session-factory>  
  5.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  6.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  7.         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull</property>  
  8.         <property name="hibernate.connection.username">root</property>  
  9.         <property name="hibernate.connection.password"> </property>  
  10.         <property name="hibernate.connection.pool_size">10</property>  
  11.         <property name="show_sql">true</property>  
  12.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  13.         <property name="hibernate.hbm2ddl.auto">update</property>  
  14.         <mapping class="com.model.pojo.User" />  
  15.         <mapping class="com.model.pojo.User" />  
  16.     </session-factory>  
  17. </hibernate-configuration>  
2. Creating Reverse Engineering File->hibernate.reveng.xml
 
 
 
Right Click default package in the Source Package->new->choose Hibernate Reverse Engineering Wizard ->click next->choose customer table->Add ->click finish.
 
Code
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">  
  3. <hibernate-reverse-engineering>  
  4.     <schema-selection match-catalog="test" />  
  5.     <table-filter match-name="user" />  
  6. </hibernate-reverse-engineering>  
3. Creating Hibernate Entity (pojo) File:-user.java
 
Important: To create this file MySQL database test most be connected through Netbeans.
 
Right click com.model package->new->Hibernate Mappling Files and pojos from database -> Do not select mapping file & select EJB3.0 Pattern -> Click Finish
 
User.java Code
  1. package com.model.pojo;  
  2. // Generated May 23, 2016 12:30:14 PM by Hibernate Tools 4.3.1  
  3. import java.util.Date;  
  4. import javax.persistence.Column;  
  5. import javax.persistence.Entity;  
  6. import javax.persistence.GeneratedValue;  
  7. import static javax.persistence.GenerationType.IDENTITY;  
  8. import javax.persistence.Id;  
  9. import javax.persistence.Table;  
  10. import javax.persistence.Temporal;  
  11. import javax.persistence.TemporalType;  
  12. /** 
  13.  * User generated by hbm2java 
  14.  */  
  15. @Entity  
  16. @Table(name = "user", catalog = "test")  
  17. public class User implements java.io.Serializable  
  18. {  
  19.     private Integer id;  
  20.     private String recordNo;  
  21.     private String name;  
  22.     private Integer age;  
  23.     private String sex;  
  24.     private Date dob;  
  25.     private String remark;  
  26.     public User()  
  27.     {}  
  28.     public User(String recordNo, String name, Integer age, String sex, Date dob, String remark)  
  29.     {  
  30.         this.recordNo = recordNo;  
  31.         this.name = name;  
  32.         this.age = age;  
  33.         this.sex = sex;  
  34.         this.dob = dob;  
  35.         this.remark = remark;  
  36.     }  
  37.     @Id @GeneratedValue(strategy = IDENTITY)  
  38.     @Column(name = "id", unique = true, nullable = false)  
  39.     public Integer getId()  
  40.     {  
  41.         return this.id;  
  42.     }  
  43.     public void setId(Integer id)  
  44.     {  
  45.         this.id = id;  
  46.     }  
  47.     @Column(name = "RecordNo", length = 20)  
  48.     public String getRecordNo()  
  49.     {  
  50.         return this.recordNo;  
  51.     }  
  52.     public void setRecordNo(String recordNo)  
  53.     {  
  54.         this.recordNo = recordNo;  
  55.     }  
  56.     @Column(name = "Name", length = 50)  
  57.     public String getName()  
  58.     {  
  59.         return this.name;  
  60.     }  
  61.     public void setName(String name)  
  62.     {  
  63.         this.name = name;  
  64.     }  
  65.     @Column(name = "Age")  
  66.     public Integer getAge()  
  67.     {  
  68.         return this.age;  
  69.     }  
  70.     public void setAge(Integer age)  
  71.     {  
  72.         this.age = age;  
  73.     }  
  74.     @Column(name = "Sex", length = 20)  
  75.     public String getSex()  
  76.     {  
  77.         return this.sex;  
  78.     }  
  79.     public void setSex(String sex)  
  80.     {  
  81.         this.sex = sex;  
  82.     }  
  83.     @Temporal(TemporalType.DATE)  
  84.     @Column(name = "Dob", length = 10)  
  85.     public Date getDob()  
  86.     {  
  87.         return this.dob;  
  88.     }  
  89.     public void setDob(Date dob)  
  90.     {  
  91.         this.dob = dob;  
  92.     }  
  93.     @Column(name = "Remark", length = 50)  
  94.     public String getRemark()  
  95.     {  
  96.         return this.remark;  
  97.     }  
  98.     public void setRemark(String remark)  
  99.     {  
  100.         this.remark = remark;  
  101.     }  
  102.     //This method writes the values of contact object with System.out.println(user.toString()) code  
  103.     @Override  
  104.     public String toString()  
  105.     {  
  106.         return "user" +  
  107.             "\n\t RecordNo: " + this.recordNo +  
  108.             "\n\t EmployeeName: " + this.name +  
  109.             "\n\t Age: " + this.age +  
  110.             "\n\t Sex: " + this.sex +  
  111.             "\n\t Date of Birth: " + this.dob +  
  112.             "\n\t Remark: " + this.remark;  
  113.     }  
  114. }  
4. Creating JSF Managed Bean File
 
UserBean.java File
 
Right click com.controller package->new-> JSF Managed Bean ->Give class name UsererBean-> click finish.
 
UserBean.java File CODE
  1. package com.controller.bean;  
  2. import javax.faces.bean.ManagedBean;  
  3. import javax.faces.bean.ViewScoped;  
  4. import java.util.List;  
  5. import com.dao.UserDAO;  
  6. import com.model.pojo.User;  
  7. import java.io.Serializable;  
  8. import org.primefaces.event.RowEditEvent;  
  9. import javax.faces.context.FacesContext;  
  10. import javax.faces.application.FacesMessage;  
  11. import org.primefaces.context.RequestContext;  
  12. /** 
  13.  * 
  14.  * @author Raichand 
  15.  */  
  16. @ManagedBean(name = "userBean")  
  17. @ViewScoped  
  18. public class UserBean implements Serializable  
  19. {  
  20.     private List < User > usersList;  
  21.     private List < User > searchList;  
  22.     private List < User > searchByRecordNoList;  
  23.     UserDAO userDao = new UserDAO();  
  24.     User user = new User();  
  25.     User newuser = new User();  
  26.     public List < User > getUsers()  
  27.     {  
  28.         usersList = userDao.AllUsers();  
  29.         int count = usersList.size();  
  30.         return usersList;  
  31.     }  
  32.     public void addUser()  
  33.     {  
  34.         String Remark = newuser.getRemark();  
  35.         Integer userId = 0;  
  36.         userId = userDao.getId();  
  37.         newuser.setId(userId);  
  38.         String Id = Integer.toString(newuser.getId());  
  39.         newuser.setRecordNo(Integer.toString(userId));  
  40.         userDao.add(newuser);  
  41.         System.out.println("User successfully saved.");  
  42.         FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information""User successfully saved.");  
  43.         RequestContext.getCurrentInstance().showMessageInDialog(message);  
  44.         newuser = new User();  
  45.     }  
  46.     public void changeUser(User user)  
  47.     {  
  48.         this.user = user;  
  49.     }  
  50.     public void UpdateUser(User user)  
  51.     {  
  52.         String Name = user.getName();  
  53.         FacesMessage message1 = new FacesMessage(FacesMessage.SEVERITY_INFO, "Name", Name);  
  54.         RequestContext.getCurrentInstance().showMessageInDialog(message1);  
  55.         userDao.update(user);  
  56.         System.out.println("User Info successfully saved.");  
  57.         FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information""User updated successfully .");  
  58.         RequestContext.getCurrentInstance().showMessageInDialog(message);  
  59.         user = new User();  
  60.     }  
  61.     public void deleteUser(User user)  
  62.     {  
  63.         String Name = user.getName();  
  64.         //FacesMessage message3= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete Item",contactName);  
  65.         // RequestContext.getCurrentInstance().showMessageInDialog(message3);  
  66.         userDao.delete(user);  
  67.         FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete""Record deleted successfully");  
  68.         RequestContext.getCurrentInstance().showMessageInDialog(message);  
  69.     }  
  70.     public void searchbyRecordno()  
  71.     {  
  72.         searchByRecordNoList = userDao.SearchByRecordNo(user.getRecordNo());  
  73.         int count = searchByRecordNoList.size();  
  74.         FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Number of Record Selected:", Integer.toString(count));  
  75.         RequestContext.getCurrentInstance().showMessageInDialog(message);  
  76.     }  
  77.     public User getUser()  
  78.     {  
  79.         return user;  
  80.     }  
  81.     public void setUser(User user)  
  82.     {  
  83.         this.user = user;  
  84.     }  
  85.     public User getNewuser()  
  86.     {  
  87.         return newuser;  
  88.     }  
  89.     public void setNewuser(User newuser)  
  90.     {  
  91.         this.newuser = newuser;  
  92.     }  
  93.     public List < User > getUsersList()  
  94.     {  
  95.         return usersList;  
  96.     }  
  97.     public void setUsersList(List < User > usersList)  
  98.     {  
  99.         this.usersList = usersList;  
  100.     }  
  101.     public List < User > getSearchList()  
  102.     {  
  103.         return searchList;  
  104.     }  
  105.     public void setSearchList(List < User > searchList)  
  106.     {  
  107.         this.searchList = searchList;  
  108.     }  
  109.     public List < User > getSearchByRecordNoList()  
  110.     {  
  111.         return searchByRecordNoList;  
  112.     }  
  113.     public void setSearchByRecordNoList(List < User > searchByRecordNoList)  
  114.     {  
  115.         this.searchByRecordNoList = searchByRecordNoList;  
  116.     }  
  117.     public void onRowEdit(RowEditEvent event)  
  118.     {  
  119.         FacesMessage msg = new FacesMessage(" Edited Record No", ((User) event.getObject()).getRecordNo());  
  120.         FacesContext.getCurrentInstance().addMessage(null, msg);  
  121.         User editeduser = (User) event.getObject();  
  122.         userDao.update(editeduser);  
  123.     }  
  124.     public void onCancel(RowEditEvent event)  
  125.     {  
  126.         FacesMessage msg = new FacesMessage("Edit Cancelled");  
  127.         FacesContext.getCurrentInstance().addMessage(null, msg);  
  128.         usersList.remove((User) event.getObject());  
  129.     }  
  130. }  
5. Creating DataAccessObject (DAO) File
 
UserDAO.java File
 
Right click com.dao package->new->JavaClass->Give class name UserDAO-> click Finish.
 
UserDAO.java File Code
  1. package com.dao;  
  2. import java.util.List;  
  3. import java.util.ArrayList;  
  4. import org.hibernate.Query;  
  5. import org.hibernate.Session;  
  6. import com.util.HibernateUtil;  
  7. import com.model.pojo.User;  
  8. import javax.faces.application.FacesMessage;  
  9. import org.primefaces.context.RequestContext;  
  10. /** 
  11.  * 
  12.  * @author Raichand 
  13.  */  
  14. public class UserDAO  
  15. {  
  16.     private User user;  
  17.     private User newuser;  
  18.     private List < User > DaoAllUsers;  
  19.     private List < User > DaoSearchUserList;  
  20.     //Session session;  
  21.     public List < User > AllUsers()  
  22.     {  
  23.         Session session = HibernateUtil.getSessionFactory().openSession();  
  24.         try  
  25.         {  
  26.             session.beginTransaction();  
  27.             DaoAllUsers = session.createCriteria(User.class).list();  
  28.             int count = DaoAllUsers.size();  
  29.             // FacesMessage message1 = new FacesMessage(FacesMessage.SEVERITY_INFO, "List Size", Integer.toString(count));//Debugging Purpose  
  30.             //RequestContext.getCurrentInstance().showMessageInDialog(message1);  
  31.             session.getTransaction().commit();  
  32.         }  
  33.         catch (Exception e)  
  34.         {  
  35.             e.printStackTrace();  
  36.             session.getTransaction().rollback();  
  37.         }  
  38.         session.close();  
  39.         return DaoAllUsers;  
  40.     }  
  41.     public Integer getId()  
  42.     {  
  43.         Session session = HibernateUtil.getSessionFactory().openSession();  
  44.         String hql = "select max(U.id) from User U";  
  45.         Query query = session.createQuery(hql);  
  46.         List < Integer > results = query.list();  
  47.         Integer userId = 1;  
  48.         if (results.get(0) != null)  
  49.         {  
  50.             userId = results.get(0) + 1;  
  51.         }  
  52.         session.flush();  
  53.         session.close();  
  54.         return userId;  
  55.     }  
  56.     public List < User > SearchByRecordNo(String RecordNo)  
  57.     {  
  58.         Session session = HibernateUtil.getSessionFactory().openSession();  
  59.         List < User > daoSearchList = new ArrayList < > ();  
  60.         try  
  61.         {  
  62.             session.beginTransaction();  
  63.             Query qu = session.createQuery("From User U where U.recordNo =:recordNo"); //User is the entity not the table  
  64.             qu.setParameter("recordNo", RecordNo);  
  65.             daoSearchList = qu.list();  
  66.             int count = daoSearchList.size();  
  67.             session.getTransaction().commit();  
  68.         }  
  69.         catch (Exception e)  
  70.         {  
  71.             e.printStackTrace();  
  72.             session.getTransaction().rollback();  
  73.         }  
  74.         finally  
  75.         {  
  76.             session.close();  
  77.         }  
  78.         return daoSearchList;  
  79.     }  
  80.     public void add(User newuser)  
  81.     {  
  82.         Session session = HibernateUtil.getSessionFactory().openSession();  
  83.         try  
  84.         {  
  85.             String Id = Integer.toString(newuser.getId());  
  86.             // begin a transaction  
  87.             session.beginTransaction();  
  88.             session.merge(newuser);  
  89.             session.flush();  
  90.             System.out.println("NewUser saved, id: " +  
  91.                 newuser.getId());  
  92.             session.getTransaction().commit();  
  93.         }  
  94.         catch (Exception e)  
  95.         {  
  96.             e.printStackTrace();  
  97.             session.getTransaction().rollback();  
  98.         }  
  99.         session.close();  
  100.     }  
  101.     public void delete(User user)  
  102.     {  
  103.         Session session = HibernateUtil.getSessionFactory().openSession();  
  104.         try  
  105.         {  
  106.             String name = user.getName();  
  107.             session.beginTransaction();  
  108.             session.delete(user);  
  109.             session.getTransaction().commit();  
  110.         }  
  111.         catch (Exception e)  
  112.         {  
  113.             e.printStackTrace();  
  114.             session.getTransaction().rollback();  
  115.         }  
  116.         session.close();  
  117.     }  
  118.     public void update(User user)  
  119.     {  
  120.         Session session = HibernateUtil.getSessionFactory().openSession();  
  121.         try  
  122.         {  
  123.             session.beginTransaction();  
  124.             session.update(user);  
  125.             session.flush();  
  126.             session.getTransaction().commit();  
  127.         }  
  128.         catch (Exception e)  
  129.         {  
  130.             e.printStackTrace();  
  131.             session.getTransaction().rollback();  
  132.         }  
  133.         session.close();  
  134.     }  
  135. }  
6. HibernateUtil.java File
 
Right click com.util folder-->new->javaclass->Class name ->Give name HibernateUtil ->Click Finish.
 
HibernateUtil.java Code
  1. package com.util;  
  2. import java.util.Properties;  
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.service.ServiceRegistry;  
  7. import com.model.pojo.User;  
  8. public class HibernateUtil  
  9. {  
  10.     //Annotation based configuration  
  11.     private static SessionFactory sessionFactory;  
  12.     private static SessionFactory buildSessionFactory()  
  13.     {  
  14.         try  
  15.         {  
  16.             // Create the SessionFactory from hibernate.cfg.xml  
  17.             Configuration configuration = new Configuration();  
  18.             configuration.configure("/hibernate.cfg.xml");  
  19.             System.out.println("Hibernate Annotation Configuration loaded");  
  20.             ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();  
  21.             System.out.println("Hibernate Annotation serviceRegistry created");  
  22.             sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
  23.             return sessionFactory;  
  24.         }  
  25.         catch (Throwable ex)  
  26.         {  
  27.             // Make sure you log the exception, as it might be swallowed  
  28.             System.err.println("Initial SessionFactory creation failed." + ex);  
  29.             throw new ExceptionInInitializerError(ex);  
  30.         }  
  31.     }  
  32.     public static SessionFactory getSessionFactory()  
  33.     {  
  34.         if (sessionFactory == null) sessionFactory = buildSessionFactory();  
  35.         return sessionFactory;  
  36.     }  
  37.     public static void shutdown()  
  38.     {  
  39.         // Close caches and connection pools  
  40.         sessionFactory.close();  
  41.     }  
  42. }  
7. Creating index.xhtml File
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">  
  3. <h:head>  
  4.     <h2><center>All User Information</center></h2>  
  5. </h:head>  
  6. <h:body>  
  7.     <h:form>  
  8.         <p:commandButton action="Search?faces-redirect=true" icon="ui-icon-search" value="Search" />  
  9.     </h:form>  
  10.   
  11.     <p:spacer> </p:spacer>  
  12.     <h:form id="form1">  
  13.         <p:dataTable id="dataTable" var="user" paginator="true" rows="5" value="#{userBean.users}">  
  14.             <p:column headerText="RecordNo">  
  15.                 <h:outputText value="#{user.recordNo}" />  
  16.             </p:column>  
  17.             <p:column headerText="Name">  
  18.                 <h:outputText value="#{user.name}" />  
  19.             </p:column>  
  20.             <p:column sortBy="#{user.age}" headerText="Age">  
  21.                 <h:outputText value="#{user.age}" />  
  22.   
  23.             </p:column>  
  24.   
  25.             <p:column headerText="Sex">  
  26.                 <h:outputText value="#{user.sex}" />  
  27.             </p:column>  
  28.             <p:column headerText="Date of Birth">  
  29.                 <h:outputText value="#{user.dob}">  
  30.                     <f:convertDateTime type="date" pattern="dd-MMM-yyyy" />  
  31.                 </h:outputText>  
  32.             </p:column>  
  33.             <p:column headerText="Remark">  
  34.                 <h:outputText value="#{user.remark}" />  
  35.             </p:column>  
  36.         </p:dataTable>  
  37.     </h:form>  
  38.     <h:panelGroup>  
  39.         <h3>Add User Information</h3>  
  40.         <h:form>  
  41.             <p>User Name:  
  42.                 <p:inputText value="#{userBean.newuser.name}" /></p>  
  43.             <p>User Age:  
  44.                 <p:inputText value="#{userBean.newuser.age}" />Enter Number Only</p>  
  45.             <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">  
  46.                 <p>Choose Sex:</p>  
  47.                 <p:selectOneMenu label="Sex:" value="#{userBean.newuser.sex}" id="ulist2">  
  48.                     <f:selectItem itemLabel="Select One" itemValue="" />  
  49.                     <f:selectItem itemLabel="Male" itemValue="Male" />  
  50.                     <f:selectItem itemLabel="Female" itemValue="Female" />  
  51.                 </p:selectOneMenu>  
  52.             </h:panelGrid>  
  53.             <p>User Date of Birth:  
  54.                 <p:calendar id="dop" value="#{userBean.newuser.dob}" label="DatePosted:" required="true" pattern="dd/MMM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Posting!" navigator="true" showButtonPanel="true" yearRange="c-60:c+60" /> </p>  
  55.             <p>Remark:  
  56.                 <p:inputTextarea value="#{userBean.newuser.remark}" /></p>  
  57.             <p>  
  58.                 <p:commandButton icon="ui-icon-plusthick" update=":form1:dataTable" type="submit" value="add" action="#{userBean.addUser()}" /></p>  
  59.         </h:form>  
  60.     </h:panelGroup>  
  61. </h:body>  
  62.   
  63. </html>  
8. Search.xhtml code
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">  
  3.   
  4. <h:head>  
  5.   
  6.     <h2><center>Search User For Edit And Delete</center></h2>  
  7. </h:head>  
  8. <h:body>  
  9.     <h:form>  
  10.   
  11.         ,  
  12.         <p:commandButton action="index?faces-redirect=true" value="Back" icon="ui-icon-arrowthick-1-w" />  
  13.   
  14.     </h:form>  
  15.   
  16.     <h:form id="form">  
  17.   
  18.         <p:growl id="messages" showDetail="true" />  
  19.         <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">  
  20.             <p:outputLabel value="Please Select Record Number:" />  
  21.             <p:selectOneMenu value="#{userBean.user.recordNo}" editable="true" label="Please Select Record Number:" filter="true" id="ulist2">  
  22.                 <f:selectItem itemLabel="Select One" itemValue="" />  
  23.                 <f:selectItems value="#{userBean.users}" var="user" itemLabel="#{user.recordNo}" itemValue="#{user}" />  
  24.   
  25.             </p:selectOneMenu>  
  26.         </h:panelGrid>  
  27.         <p:commandButton value="Search" update=":form:userTable" type="Submit" icon="ui-icon-search" action="#{userBean.searchbyRecordno()}" />  
  28.         <br/>  
  29.         <p:spacer> </p:spacer>  
  30.   
  31.         <p:dataTable var="user" id="userTable" editable="true" value="#{userBean.searchByRecordNoList}">  
  32.             <f:facet name="header">  
  33.                 Row Editing  
  34.             </f:facet>  
  35.             <p:ajax event="rowEdit" listener="#{userBean.onRowEdit}" update=":form:messages" />  
  36.             <p:ajax event="rowEditCancel" listener="#{userBean.onCancel}" update=":form:messages" />  
  37.   
  38.             <p:column headerText="RecordNo">  
  39.                 <p:cellEditor>  
  40.                     <f:facet name="output">  
  41.                         <h:outputText value="#{user.recordNo}" />  
  42.                     </f:facet>  
  43.                     <f:facet name="input">  
  44.                         <p:inputText id="modelInput" value="#{user.recordNo}" style="width:100%" />  
  45.                     </f:facet>  
  46.                 </p:cellEditor>  
  47.             </p:column>  
  48.   
  49.             <p:column headerText=" Name">  
  50.                 <p:cellEditor>  
  51.                     <f:facet name="output">  
  52.                         <h:outputText value="#{user.name}" />  
  53.                     </f:facet>  
  54.                     <f:facet name="input">  
  55.                         <p:inputText value="#{user.name}" style="width:100%" />  
  56.                     </f:facet>  
  57.                 </p:cellEditor>  
  58.   
  59.             </p:column>  
  60.   
  61.             <p:column headerText="Age">  
  62.                 <p:cellEditor>  
  63.                     <f:facet name="output">  
  64.                         <h:outputText value="#{user.age}" />  
  65.                     </f:facet>  
  66.                     <f:facet name="input">  
  67.                         <p:inputText value="#{user.age}" style="width:100%" />  
  68.                     </f:facet>  
  69.                 </p:cellEditor>  
  70.             </p:column>  
  71.             <p:column headerText="Date of Birth">  
  72.                 <p:cellEditor>  
  73.                     <f:facet name="output">  
  74.                         <h:outputText value="#{user.dob}">  
  75.                             <f:convertDateTime type="date" pattern="dd-MMM-yyyy" />  
  76.                         </h:outputText>  
  77.                     </f:facet>  
  78.   
  79.                     <f:facet name="input">  
  80.                         <p:calendar id="dob" value="#{user.dob}" style="width:100%" label="DatePosted:" required="true" pattern="dd/MM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!" navigator="true" showButtonPanel="true" yearRange="c-60:c+60" />  
  81.                     </f:facet>  
  82.                 </p:cellEditor>  
  83.             </p:column>  
  84.             <p:column headerText="Sex" width="100">  
  85.                 <p:cellEditor>  
  86.                     <f:facet name="output">  
  87.                         <h:outputText value="#{user.sex}" />  
  88.                     </f:facet>  
  89.                     <f:facet name="input">  
  90.                         <p:selectOneMenu value="#{user.sex}" id="ulist11">  
  91.                             <f:selectItem itemLabel="Select One" itemValue="" />  
  92.                             <f:selectItem itemLabel="Male" itemValue="Male" />  
  93.                             <f:selectItem itemLabel="Female" itemValue="Female" />  
  94.                         </p:selectOneMenu>  
  95.                     </f:facet>  
  96.                 </p:cellEditor>  
  97.             </p:column>  
  98.             <p:column headerText="Remark">  
  99.                 <p:cellEditor>  
  100.                     <f:facet name="output">  
  101.                         <h:outputText value="#{user.remark}" />  
  102.                     </f:facet>  
  103.                     <f:facet name="input">  
  104.                         <p:inputText value="#{user.remark}" style="width:100%" />  
  105.                     </f:facet>  
  106.                 </p:cellEditor>  
  107.             </p:column>  
  108.             <p:column headerText="Edit" style="width:100px">  
  109.                 <p:rowEditor />  
  110.             </p:column>  
  111.             <p:column headerText="Delete">  
  112.   
  113.                 <p:commandButton value="Delete" icon="ui-icon-trash" update="form:userTable" type="button" onclick="PF('confirmDialog').show()" />  
  114.                 <p:confirmDialog message="Are you sure you want to delete this record?Record once deleted can not be retrieved." header="Deleting" severity="alert" widgetVar="confirmDialog">  
  115.                     <p:commandButton value="Yes Sure" action="#{userBean.deleteUser(user)}" oncomplete="PF('confirmDialog').hide()" />  
  116.   
  117.                     <p:commandButton value="Not Yet" onclick="PF('confirmDialog').hide();" type="button" />  
  118.                 </p:confirmDialog>  
  119.             </p:column>  
  120.         </p:dataTable>  
  121.     </h:form>  
  122. </h:body>  
  123.   
  124. </html>  
9. UserCRUD.xhtml
 
Under the webpages folder welcome.xhtml file is automatically generated.
 
Right click welcome.xhtml file->Refactor->rename->Givename UserCRUD->click finish.
 
It is a single page CRUD Project. It is an independent file. It can be run by selecting it in TOC then File(From Menu)->Run File.
 
UserCRUD.xhtml Code
  1. <?xml version='1.0' encoding='UTF-8' ?>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">  
  4. <h:head>  
  5.     <title>User CRUD</title>  
  6. </h:head>  
  7. <h:body>  
  8.     <p:dialog id="userDetail1" widgetVar="$userDetail1" header="Add User" hideEffect="explode" appendTo="@(body)" resizable="false" draggable="false" closeOnEscape="true">  
  9.         <h:form>  
  10.   
  11.             <p:panelGrid columns="2">  
  12.                 <h:outputLabel for="username" value="User Name: *" />  
  13.                 <p:inputText id="username" value="#{userBean.newuser.name}" label="User Name" placeholder="User Name" />  
  14.   
  15.                 <h:outputLabel for="userage" value="User Age" />  
  16.                 <p:inputText id="userage" label="User Age" value="#{userBean.newuser.age}" placeholder="age" />  
  17.   
  18.                 <h:outputLabel for="sex" value="Choose Sex" />  
  19.                 <p:selectOneMenu id="sex" label="Choose Sex" value="#{userBean.newuser.sex}" effect="fold">  
  20.                     <f:selectItem itemLabel="Select One" itemValue="" />  
  21.                     <f:selectItem itemLabel="Male" itemValue="Male" />  
  22.                     <f:selectItem itemLabel="Female" itemValue="Female" />  
  23.                 </p:selectOneMenu>  
  24.                 <p:outputLabel for="dob" value="User Date of Birth" />  
  25.   
  26.                 <p:calendar id="dob" value="#{userBean.newuser.dob}" label="DatePosted:" required="true" pattern="dd/MM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!" navigator="true" showButtonPanel="true" yearRange="c-60:c+60" placeholder="Date of Birth" />  
  27.   
  28.                 <p:outputLabel for="remark" value="Remark" />  
  29.                 <p:inputTextarea id="remark" label="Remark" value="#{userBean.newuser.remark}" placeholder="Remark" />  
  30.   
  31.                 <p:commandButton value="add" process="@form" id="AddButtonId" ajax="true" icon="ui-icon-plus" update=":form1:userTable" actionListener="#{userBean.addUser()}" oncomplete="PF('$userDetail1').hide()" />  
  32.   
  33.                 <p:commandButton id="cancelAddButtonId" value="Cancel" onclick="handleComplete(xhr, status, args)" />  
  34.             </p:panelGrid>  
  35.         </h:form>  
  36.   
  37.     </p:dialog>  
  38.     <h:outputScript>  
  39.         /* 
  40.         <![CDATA[ */  
  41. function handleComplete(xhr, status, args) {  
  42. if(args && args.validName) {  
  43. $userDetail1.hide();  
  44. }  
  45. }  
  46. /* ]]>*/  
  47.   
  48.     </h:outputScript>  
  49.     <p:dialog id="userDetail2" widgetVar="$userDetail2" header="Update User" hideEffect="explode" appendTo="@(body)" resizable="false" draggable="false" closeOnEscape="true">  
  50.         <h:form>  
  51.             <h:inputHidden value="#{userBean.user.id}" />  
  52.             <p:panelGrid columns="2">  
  53.                 <h:outputLabel for="recordno" value="Record No: *" />  
  54.                 <p:inputText id="recordno" value="#{userBean.user.recordNo}" label="Record No" placeholder="Record No" />  
  55.                 <h:outputLabel for="username" value="User Name: *" />  
  56.                 <p:inputText id="username" value="#{userBean.user.name}" label="User Name" placeholder="User Name" />  
  57.   
  58.                 <h:outputLabel for="userage" value="User Age" />  
  59.                 <p:inputText id="userage" label="User Age" value="#{userBean.user.age}" placeholder="age" />  
  60.   
  61.                 <h:outputLabel for="sex" value="Choose Sex" />  
  62.                 <p:selectOneMenu id="sex" label="Choose Sex" value="#{userBean.user.sex}" effect="fold">  
  63.                     <f:selectItem itemLabel="Select One" itemValue="" />  
  64.                     <f:selectItem itemLabel="Male" itemValue="Male" />  
  65.                     <f:selectItem itemLabel="Female" itemValue="Female" />  
  66.                 </p:selectOneMenu>  
  67.                 <p:outputLabel for="dob" value="User Date of Birth" />  
  68.   
  69.                 <p:calendar id="dob" value="#{userBean.user.dob}" label="DatePosted:" required="true" pattern="dd/MM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!" navigator="true" showButtonPanel="true" yearRange="c-60:c+60" placeholder="Date of Birth" />  
  70.   
  71.                 <p:outputLabel for="remark" value="Remark" />  
  72.                 <p:inputTextarea id="remark" label="Remark" value="#{userBean.user.remark}" placeholder="Remark" />  
  73.   
  74.                 <p:commandButton value="Update" ajax="true" icon="ui-icon-disk" update=":form1:userTable" actionListener="#{userBean.UpdateUser(userBean.user)}" oncomplete="handleComplete(xhr, status, args)" />  
  75.                 <p:commandButton value="Cancel" id="cancelButtonId" onclick="handleComplete(xhr, status, args)" />  
  76.             </p:panelGrid>  
  77.         </h:form>  
  78.   
  79.     </p:dialog>  
  80.     <h:outputScript id="handleCompleteScript" target="body">  
  81.         /* 
  82.         <![CDATA[ */  
  83. function handleComplete(xhr, status, args) {  
  84. if(args && args.validName) {  
  85. $userDetail2.hide();  
  86. }  
  87. }  
  88. /* ]]>*/  
  89.     </h:outputScript>  
  90.   
  91.     <h:form id="form1">  
  92.         <p:commandButton icon="ui-icon-plusthick" id="addUserBtn" value="Add User"  update=":userDetail1" ajax="true" oncomplete="PF('$userDetail1').show()" />  
  93.   
  94.         <p:dataTable value="#{userBean.users}" var="user" paginator="true" rows="5" id="userTable">  
  95.             <p:column headerText="Record No" style="text-align: left;">  
  96.                 <h:outputText value="#{user.recordNo}" />  
  97.             </p:column>  
  98.             <p:column headerText="Name">  
  99.                 #{user.name}  
  100.             </p:column>  
  101.             <p:column sortBy="#{user.age}" headerText="Age">  
  102.                 <h:outputText value="#{user.age}" />  
  103.   
  104.             </p:column>  
  105.             <p:column headerText="Sex">  
  106.                 <h:outputText value="#{user.sex}" />  
  107.             </p:column>  
  108.   
  109.             <p:column headerText="Date of Birth">  
  110.                 <h:outputText value="#{user.dob}">  
  111.                     <f:convertDateTime type="date" pattern="dd-MMM-yyyy" />  
  112.                 </h:outputText>  
  113.             </p:column>  
  114.             <p:column headerText="Remark">  
  115.                 <h:outputText value="#{user.remark}" />  
  116.             </p:column>  
  117.             <p:column headerText="Edit" style="text-align: center">  
  118.                 <p:commandButton icon="ui-icon-pencil" id="editUserBtn" value="Edit" ajax="true" actionListener="#{userBean.changeUser(user)}" update=":userDetail2" oncomplete="PF('$userDetail2').show()" />  
  119.   
  120.             </p:column>  
  121.   
  122.             <p:column headerText="Delete" style="text-align: center">  
  123.   
  124.                 <p:commandButton value="Delete" icon="ui-icon-trash" type="button" onclick="PF('confirmDialog').show()" />  
  125.                 <p:confirmDialog message="Are you sure you want to delete this record?Record once deleted can not be retrieved." header="Deleting" severity="alert" widgetVar="confirmDialog">  
  126.                     <p:commandButton value="Yes Sure" update=":form1:userTable" action="#{userBean.deleteUser(user)}" oncomplete="PF('confirmDialog').hide()" />  
  127.   
  128.                     <p:commandButton value="Not Yet" onclick="PF('confirmDialog').hide();" type="button" />  
  129.                 </p:confirmDialog>  
  130.   
  131.             </p:column>  
  132.             <p:rowExpansion>  
  133.                 <h:outputText value="#{user.remark}" styleClass="rowExpansion" />  
  134.             </p:rowExpansion>  
  135.         </p:dataTable>  
  136.     </h:form>  
  137.   
  138. </h:body>  
  139.   
  140. </html>  
10. web.xml (Automatically generated)
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">  
  3.     <context-param>  
  4.         <param-name>javax.faces.PROJECT_STAGE</param-name>  
  5.         <param-value>Development</param-value>  
  6.     </context-param>  
  7.     <servlet>  
  8.         <servlet-name>Faces Servlet</servlet-name>  
  9.         <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
  10.         <load-on-startup>1</load-on-startup>  
  11.     </servlet>  
  12.     <servlet-mapping>  
  13.         <servlet-name>Faces Servlet</servlet-name>  
  14.         <url-pattern>*.xhtml</url-pattern>  
  15.     </servlet-mapping>  
  16.     <session-config>  
  17.         <session-timeout>  
  18.             30  
  19.         </session-timeout>  
  20.     </session-config>  
  21.     <welcome-file-list>  
  22.         <welcome-file>index.xhtml</welcome-file>  
  23.     </welcome-file-list>  
  24. </web-app>  
 
 
Figure: Project Structure
 
Select the project in project window and run the project.
 
Index.xhtml page
 
 
 
Search.xhtml Page
 
 
 
Search.xhtml Page before deleting Record
 
 
 
UserCRUD.xhtml page
 
Select UserCRUD.xhtml page in TOC then choose File From Menuļƒ Run File
 
 


Similar Articles