Primefaces5, Spring4, Hibernate4, CRUD Using Netbeans 8.02 And MySQL5 Database Server

Introduction 

 
This is a Create, Read, Update and Delete application operating on a ‘Customer’ table in ‘test’ database of MySQL database Server. It is a Hibernate-Annotation and Spring-XML based application. It uses Hibernate 4 as a Data Access layer, PrimeFaces 5 as a UI framework, and Spring 4 in the business layer. The beauty of this combination is that there are very limited configurations through XML and by annotations. This gives more flexibility to the developers just to concentrate on the UI and business layer.
 
Software used.
  1. JDK8u25
  2. Netbeans 8.02
  3. MySQL 5.* Database Server(or XAMPP, for easy MySQL management)
  4. MySQL Connector 5.*
  5. Hibernate 4.3.**, Spring4MVC 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).
  4. After installing Netbeans, click the Services tab on the left. 
  5. Expand the Database node
  6. Expand the Drivers node. 
  7. Right-click on MySQL(Connector/Jdriver), then Connect
  8. Give the database name as a test
  9. As shown below, put the password, if you have given it while installing the MySQL Database Server. However, no password is required for XAMPP. 
  10. Then, Test Connection. If successful, click Finish.
finish
 
Create a user table by running the below SQL query in the ‘test’ database. 
  1. CREATE TABLE IF NOT EXISTS `customer` (  
  2. `id` int(10) unsigned NOT NULL,  
  3. `FirstName` varchar(45) DEFAULT NULL,  
  4. `LastName` varchar(30) DEFAULT NULL,  
  5. `Sex` varchar(30) DEFAULT NULL,  
  6. `dob` date DEFAULT NULL,  
  7. `Remark` varchar(30) DEFAULT NULL  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  
  9.   
  10. ALTER TABLE `customer` ADD PRIMARY KEY (`id`);  
Insert these records by executing the following INSERT statement.
  1. INSERT INTO `customer` (`id`, `FirstName`, `LastName`, `Sex`, `dob`, `Remark`) VALUES  
  2. (1, 'Richard''Branson''Male''2001-02-16''Good person'),  
  3. (2, 'Raghu''sahu''Male''2003-07-09''good person'),  
  4. (3, 'Sujata''Mishra''Female''1969-07-16''Good Person'),  
  5. (4, 'Simadri''Dhal''Male''2003-07-01''Good Person'),  
  6. (5, 'Aradhana''Ray''Female''2002-09-02''Naughty Girl'),  
  7. (6, 'Sibananda''Ray''Male''1972-07-17''Good Person'),  
  8. (7, 'SWATI''MISHRA''Female''2003-03-18''GOOD GIRL'),  
  9. (8, 'Maria''Sharpova''Female''1980-04-08''Very Good Tennis Player');  
JARS are required to be added to Libraries folder. Right click on the Libraries folder - add JAR/Folder. Then, add the below mentioned JAR files.
  1. aopalliance-1.0.jar
  2. javax.inject-1.jar
  3. commons-logging-1.2.jar
  4. mysql-connector-java.bin.jar
Important: All the above JAR files are available for download from the provided downloadable WINRAR file, along with the other files of the project.
 

Creating the project Primefaces5Spring4Hibernate4CustomerCRUD

 
Go to File >> New Project >> Categories.
 
Choose JavaWeb >> Select WebApplication >> click Next.
 
Give Project Name as PrimefaesSpring4Hibernate4CRUD and click Next.
 
Choose Framework First Hibernate, then Java Server Faces.
 
Click Component Tab >>Choose Primefaces >> Spring MVC and click Finish.
 
Project
  
Project
  
In the above figure, Database Connection should be with the ‘test’ database.
  
test
  
Download mysql-connector-java-bin.jar. Add it to Libraries folder by right-clicking addJAR/Folder and adding the mysql-java-bin.jar.
  
Delete JSP folder with the content and dispatcher-servlet.xml under WEB-INF folder.
  
Delete index.html and redirect.jsp.
 
Create a folder named as View under the Webpages folder.
 
Right-click on Refactor and rename welcomePrimefaces.xhtml to index.xhtml.
 
Drag index.xhtml and place it inside the View folder.
 
Project Structure
  
Project Structure
  
Creating Packages and Classes
  
Right-click on Source Package folder and create four packages.
  1. com.ray.bean.controller-->This would contain JSF managed bean class CustomerBBean.java
  2. com.ray.dao-This would contain DAO (Data Access Object) class and interface CustomerDAO.java and ICustomerDAO.java.
  3. com.ray.pojo.model-This would contain entity (POJO) class Customer.java. POJO Stands for Plain Old Java Objects.
  4. com.ray.spring.service-This would contain Spring Service class and interface.
CustomerService.java and ICustomerService.java
  
Default package contains two files, hibernate.cfg.xml and hibernate.reveng.xml.
  
The following files would be created, using Netbeans.
  1. hibernate.cfg,xml file is automatically generated. (It will be used to create Customer.java and deleted.)
  2. Reverse Engineering File hibernate.reveng.xml. (It will be used to create Customer.java and deleted.)
  3. Entity (POJO) File Customer.java(POJO stands for Plain Old Java Objects)
  4. JSF managed bean file CustomerBBean.java
  5. DataAccessObject(DAO) file ICustomerDao.java
  6. DataAccessObject(DAO) file CustomerDao.java
  7. SpringService file ICustomerService.java
  8. SpringService file CustomerService.java
  9. Index.xhtml Adds new Customer, edit Customer, delete Customer and displays all Customers' information
  10. add.xhtml It is an independent file to be run independently, by selecting it in the project explorer and running it by Run(From Menu) >> Run File.
  11. faces-config.xml It is to be added after creating under WEB-INF folder.
  12. web.xml (Automatically generated).
  13. applicationContext.xml (Automatically generated under WEB-INF folder and to be modified.) Add mysql- connector-java-bin.jar to Libraries if not done.
Copy and paste the code for the files whose code is not generated.
  1. Hibernate.cfg.xml File (It would be deleted after used for creating Customer.java entity class). As XAMPP is used, so there is no password in the file. Only username is given which 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.ray.pojo.model.Customer"/>  
    15.   </session-factory>  
    16. </hibernate-configuration>  
  2. Creating Reverse Engineering File - hibernate.reveng.xml (It would be deleted after it is used for creating Customer.java entity class).
     
    new
            
    Right click on default package in the Source Package. Go to Ne >> 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="customer"/>  
    6. </hibernate-reverse-engineering>  
  3. Creating a Hibernate Entity (POJO) file Customer.java.
     
    Important: To create this file, test, the MySQL database must be connected through Netbeans.
      
    Right-click com.model package >> New >> Hibernate Mapping Files and POJOs from the database. Do not select the mapping file and select the EJB3.0 Pattern and Domain Code (java).
      
    Click Finish.
      
    new
     
    Customer.java CODE
    1. package com.ray.pojo.model;  
    2. // Generated Jul 10, 2016 12:13:42 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.Id;  
    7. import javax.persistence.Table;  
    8. import javax.persistence.Temporal;  
    9. import javax.persistence.TemporalType;  
    10.   
    11. /** 
    12.  * Customer generated by hbm2java 
    13.  */  
    14. @Entity  
    15. @Table(name="customer"  
    16.     ,catalog="test"  
    17. )  
    18. public class Customer  implements java.io.Serializable {  
    19.      private int id;  
    20.      private String firstName;  
    21.      private String lastName;  
    22.      private String sex;  
    23.      private Date dob;  
    24.      private String remark;  
    25.   
    26.     public Customer() {  
    27.     }     
    28.     public Customer(int id) {  
    29.         this.id = id;  
    30.     }  
    31.     public Customer(int id, String firstName, String lastName, String sex, Date dob, String remark) {  
    32.        this.id = id;  
    33.        this.firstName = firstName;  
    34.        this.lastName = lastName;  
    35.        this.sex = sex;  
    36.        this.dob = dob;  
    37.        this.remark = remark;  
    38.     }     
    39.      @Id       
    40.     @Column(name="id", unique=true, nullable=false)  
    41.     public int getId() {  
    42.         return this.id;  
    43.     }      
    44.     public void setId(int id) {  
    45.         this.id = id;  
    46.     }      
    47.     @Column(name="FirstName", length=45)  
    48.     public String getFirstName() {  
    49.         return this.firstName;  
    50.     }      
    51.     public void setFirstName(String firstName) {  
    52.         this.firstName = firstName;  
    53.     }      
    54.     @Column(name="LastName", length=30)  
    55.     public String getLastName() {  
    56.         return this.lastName;  
    57.     }      
    58.     public void setLastName(String lastName) {  
    59.         this.lastName = lastName;  
    60.     }      
    61.     @Column(name="Sex", length=30)  
    62.     public String getSex() {  
    63.         return this.sex;  
    64.     }      
    65.     public void setSex(String sex) {  
    66.         this.sex = sex;  
    67.     }  
    68.     @Temporal(TemporalType.DATE)  
    69.     @Column(name="dob", length=10)  
    70.     public Date getDob() {  
    71.         return this.dob;  
    72.     }      
    73.     public void setDob(Date dob) {  
    74.         this.dob = dob;  
    75.     }      
    76.     @Column(name="Remark", length=30)  
    77.     public String getRemark() {  
    78.         return this.remark;  
    79.     }      
    80.     public void setRemark(String remark) {  
    81.         this.remark = remark;  
    82.     }  
    83.        public void reset() {  
    84.         this.setId(0);  
    85.         this.setFirstName("");  
    86.                 this.setLastName("");  
    87.                 this.setSex("");  
    88.                 this.setDob(null);  
    89.                 this.setRemark("");  
    90.     }  
    91.          
    92.     //This method writes the values of contact object with System.out.println(customer.toString()) code  
    93.     @Override  
    94.     public String toString() {  
    95.     return "customer"  
    96.     + "\n\t Id: " + this.id     
    97.     + "\n\t FirstName: " + this.firstName         
    98.     + "\n\t LastNmae: " + this.lastName  
    99.     + "\n\t Sex: " + this.sex  
    100.     + "\n\t Date of Birth: " + this.dob  
    101.     + "\n\t Remark: " + this.remark;  
    102.     }  
    103. }  
  4. Creating JSF Managed Bean file
     
    CustomerBBean.java File
     
    Right click com.controller package >> New >> JSF Managed Bean >> give class name as CustomerBBean(BackingBean) and click Finish.
     
    CustomerBBean.java File CODE
    1. package com.ray.bean.controller;  
    2. import java.io.Serializable;  
    3. import java.util.ArrayList;  
    4. import java.util.List;  
    5. import javax.faces.application.FacesMessage;  
    6. import javax.faces.context.FacesContext;  
    7. import javax.inject.Inject;  
    8. import javax.inject.Named;  
    9. import org.springframework.context.annotation.Scope;  
    10. import org.springframework.dao.DataAccessException;  
    11. import com.ray.pojo.model.Customer;  
    12. import com.ray.spring.service.ICustomerService;  
    13. import java.util.Date;  
    14. import org.primefaces.context.RequestContext;  
    15.   
    16. /** 
    17.  * Customer Backed Bean 
    18.  * @author Raichand 
    19.  */  
    20. @Named("customerBBean")  
    21. @Scope("session")  
    22. public class CustomerBBean implements Serializable {  
    23.       
    24.     private static final long serialVersionUID = 1L;  
    25.     @Inject  
    26.        private ICustomerService customerService;  
    27.        private List<Customer> customerList;  
    28.         private Customer customer = new Customer();  
    29.         private List<Customer> selectedCustomers;  
    30.         private Customer selectedCustomer;     
    31.      
    32.     /** 
    33.      * Creates a new instance of CustomerBBean 
    34.      */  
    35.     public CustomerBBean() {  
    36.     }  
    37.       
    38.     public void addCustomer() {  
    39.         try {  
    40.                                            
    41.             int newId =  getCustomerService().getNewCustomerId();//Retrieving Id og last Customer in Customer Table and adding 1 to it for next record id  
    42.                       customer.setId(newId);  
    43.                       getCustomerService().addCustomer(customer);  
    44.                         this.reset();                         
    45.                         RequestContext.getCurrentInstance().update("customerTable");//updating datatable from backing bean  
    46.                          FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save ","Customer Information saved successfully.");  
    47.                 RequestContext.getCurrentInstance().showMessageInDialog(message);  
    48.                 FacesContext.getCurrentInstance().addMessage(nullnew FacesMessage(FacesMessage.SEVERITY_INFO, "Added!""Message: "));    
    49.               
    50.         } catch (DataAccessException e) {  
    51.             e.printStackTrace();  
    52.             FacesContext.getCurrentInstance().addMessage(nullnew FacesMessage(FacesMessage.SEVERITY_ERROR, "D'oh!""Message: "));   
    53.         }         
    54.     }      
    55.         public void changeCustomer(Customer customer) {  
    56.         this.customer= customer;  
    57.            
    58.     }  
    59.           
    60.          public void updateCustomer(){              
    61.         String FirstName = customer.getFirstName();  
    62.                  FacesMessage message1= new FacesMessage(FacesMessage.SEVERITY_INFO, "FirstName",FirstName);  
    63.                 RequestContext.getCurrentInstance().showMessageInDialog(message1);  
    64.                 getCustomerService().updateCustomer(customer);        
    65.         System.out.println("Customer Info successfully saved.");  
    66.                   FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save","Customer Information updated successfully .");  
    67.                 RequestContext.getCurrentInstance().showMessageInDialog(message);  
    68.                 this.reset();              
    69.     }  
    70.           
    71.         public void deleteCustomer(){  
    72.           //String FirstName = customer.getFirstName();  
    73.          // System.out.println(FirstName);  
    74.          getCustomerService().deleteCustomer(selectedCustomers);          
    75.           FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Customer Record deleted successfully");   
    76.          RequestContext.getCurrentInstance().showMessageInDialog(message);           
    77.         RequestContext.getCurrentInstance().update("customerTable");//updating datatable from backing bean  
    78.     }  
    79.     public void reset() {  
    80.                 this.customer.setId(0);  
    81.         this.customer.setFirstName("");  
    82.                 this.customer.setLastName("");  
    83.                 this.customer.setSex("");  
    84.                 this.customer.setDob(null);  
    85.                 this.customer.setRemark("");  
    86.     }  
    87.     public List<Customer> getCustomerList() {  
    88.         customerList = new ArrayList<Customer>();  
    89.         customerList.addAll(getCustomerService().getCustomers());  
    90.         return customerList;  
    91.     }              
    92.         public ICustomerService getCustomerService() {  
    93.         return customerService;  
    94.     }  
    95.     public void setCustomerService(ICustomerService customerService) {  
    96.         this.customerService = customerService;  
    97.     }  
    98.   
    99.      
    100.     public void setCustomerList(List<Customer> customerList) {  
    101.         this.customerList = customerList;  
    102.     }       
    103.      public Customer getCustomer() {  
    104.         return customer;  
    105.     }  
    106.     public void setCustomer(Customer customer) {  
    107.         this.customer = customer;  
    108.     }        
    109.   public List<Customer> getSelectedCustomers() {  
    110.         return selectedCustomers;  
    111.     }  
    112.     public void setSelectedCustomers(List<Customer> selectedCustomers) {  
    113.         this.selectedCustomers = selectedCustomers;  
    114.     }      
    115.      public Customer getSelectedCustomer() {  
    116.         return selectedCustomer;  
    117.     }  
    118.     public void setSelectedCustomer(Customer selectedCustomer) {  
    119.         this.selectedCustomer = selectedCustomer;  
    120.     }     
    121.       
    122. }  
  5. Creating DataAccessObject (DAO) Interface file
     
    ICustomerDAO.java File
     
    Right click com.ray.dao package >> New >> JavaClass. Give class name ICustomerDAO and click Finish.
     
    ICustomerDAO.java File CODE
    1. package com.ray.dao;  
    2. import java.util.List;  
    3. import com.ray.pojo.model.Customer;  
    4. /** 
    5.  * 
    6.  * @author Raichand 
    7.  */  
    8. public interface ICustomerDAO {      
    9.     public void addCustomer(Customer customer);  
    10.    public void updateCustomer(Customer customer);                 
    11.    public int getNewCustomerId();     
    12.    public Customer getCustomer(int id);  
    13.    public List<Customer> getCustomers();          
    14.   public void deleteCustomer(List<Customer> customer);  
    15. }  
  6. Creating DataAccessObject (DAO)Class File
     
    CustomerDAO.java File
     
    Right click com.ray.dao package >> New >> JavaClass. Give class name as CustomerDAO and click Finish.
     
    CustomerDAO.java File CODE
    1. package com.ray.dao;  
    2.   
    3. import java.util.List;  
    4. import java.util.Iterator;  
    5. import javax.inject.Inject;  
    6. import javax.inject.Named;  
    7. import org.hibernate.HibernateException;  
    8. import org.hibernate.Session;  
    9. import org.hibernate.SessionFactory;  
    10. import org.hibernate.Transaction;  
    11. import com.ray.dao.ICustomerDAO;  
    12. import com.ray.pojo.model.Customer;  
    13. /** 
    14.  * Customer DAO 
    15.  * @author Raichand 
    16.  */  
    17. @Named  
    18. public class CustomerDAO implements ICustomerDAO{  
    19.       
    20.     @Inject  
    21.     private SessionFactory sessionFactory;  
    22.     public SessionFactory getSessionFactory() {  
    23.         return sessionFactory;  
    24.     }  
    25.     public void setSessionFactory(SessionFactory sessionFactory) {  
    26.         this.sessionFactory = sessionFactory;  
    27.     }  
    28.         @Override  
    29.     public void addCustomer(Customer customer) {  
    30.            int id = customer.getId();  
    31.            System.out.println("New DAO Customer Id:-"+id);  
    32.             String firstname = customer.getFirstName();  
    33.             System.out.println(firstname);  
    34.         Session session = getSessionFactory().getCurrentSession();  
    35.         Transaction trans = session.beginTransaction();  
    36.                 session.persist(customer);  
    37.         trans.commit();  
    38.     }           
    39.         @Override  
    40.     public void updateCustomer(Customer customer) {  
    41.         Session session = getSessionFactory().getCurrentSession();  
    42.         Transaction trans = session.beginTransaction();  
    43.         session.update(customer);  
    44.         trans.commit();  
    45.     }  
    46.        @Override  
    47.     public Customer getCustomer(int id) {  
    48.         Session session = getSessionFactory().getCurrentSession();  
    49.         Transaction trans = session.beginTransaction();  
    50.           
    51.         List<?> list = session  
    52.         .createQuery("from Customer where id=?").setParameter(0, id)  
    53.                 .list();          
    54.         trans.commit();  
    55.         return (Customer) list.get(0);  
    56.     }  
    57.           
    58.   
    59. //This returns new id of new customer which will be saved in customer table of test database.  
    60.         @Override  
    61.     public int getNewCustomerId() {  
    62.              Session session = sessionFactory.getCurrentSession();  
    63.              Transaction trans = session.beginTransaction();  
    64.      String query = "SELECT max(c.id) FROM Customer c";  
    65.      List list = session.createQuery(query).list();  
    66.      int maxId = ((Integer) list.get(0)).intValue();  
    67.             trans.commit();  
    68.         return (maxId+1)  ;  
    69.     }  
    70.         @SuppressWarnings("unchecked")  
    71.          @Override  
    72.     public List<Customer> getCustomers() {  
    73.         Session session = getSessionFactory().getCurrentSession();  
    74.         Transaction trans = session.beginTransaction();                
    75.                 List<Customer> list =  session.createQuery("from Customer").list();  
    76.         trans.commit();  
    77.         return list;  
    78.     }  
    79.           
    80.         @Override  
    81.     public void deleteCustomer(List<Customer> customers) {  
    82.         Session session = sessionFactory.openSession();  
    83.         Transaction tx = null;  
    84.         try {  
    85.             tx = session.beginTransaction();  
    86.             for (Iterator iterator = customers.iterator(); iterator.hasNext();) {  
    87.                 Customer customer = (Customer) iterator.next();  
    88.                 session.delete(customer);  
    89.             }  
    90.   
    91.             tx.commit();  
    92.         } catch (HibernateException e) {  
    93.             if (tx != null)  
    94.                 tx.rollback();  
    95.             e.printStackTrace();  
    96.         } finally {  
    97.             session.close();  
    98.         }  
    99.     }      
    100. }  
  7. ICustomerService.java Interface File
      
    Right click com.ray.spring.service folder >> New >> Javaclass >> Class name >> Give name as ICustomerService and click Finish.
     
    ICustomerServicel.java CODE
    1. package com.ray.spring.service;  
    2. import java.util.List;  
    3. import com.ray.pojo.model.Customer;  
    4. /** 
    5.  * Customer Service Interface 
    6.  * @author Raichand 
    7.  */  
    8. public interface ICustomerService {      
    9.         public void addCustomer(Customer customer);   
    10.         public void updateCustomer(Customer customer);            
    11.        public int getNewCustomerId();          
    12.        public Customer getCustomerById(int id);   
    13.       public List<Customer> getCustomers();          
    14.       public void deleteCustomer(List<Customer> customers);  
    15.       
    16. }  
  8. CustomerService.java Class File
     
    Right click com.ray.spring.service folder >> New >> Java Class >> Class name. Give name as CustomerService and click Finish.
     
    CustomerServicel.java CODE
    1. package com.ray.spring.service;  
    2.   
    3. import java.util.List;  
    4. import javax.inject.Inject;  
    5. import javax.inject.Named;  
    6. import org.springframework.transaction.annotation.Transactional;  
    7. import com.ray.pojo.model.Customer;  
    8. import com.ray.dao.ICustomerDAO;  
    9. import com.ray.spring.service.ICustomerService;  
    10.   
    11.   
    12. /** 
    13.  * Customer Service 
    14.  * @author Raichand 
    15.  */  
    16. @Named  
    17. @Transactional(readOnly = true)  
    18. public class CustomerService implements ICustomerService{      
    19.     @Inject  
    20.     ICustomerDAO customerDAO;  
    21.     @Transactional(readOnly = false)  
    22.         @Override  
    23.     public void addCustomer(Customer customer) {  
    24.         getCustomerDAO().addCustomer(customer);  
    25.     }  
    26.               
    27.         @Transactional(readOnly = false)  
    28.         @Override  
    29.     public void deleteCustomer(List<Customer> customers) {          
    30.           
    31.                 getCustomerDAO().deleteCustomer(customers);       
    32.     }  
    33.   
    34.     @Transactional(readOnly = false)  
    35.         @Override  
    36.     public void updateCustomer(Customer customer) {  
    37.         getCustomerDAO().updateCustomer(customer);  
    38.     }  
    39.   
    40.           
    41.         @Override  
    42.     public Customer getCustomerById(int id) {  
    43.         return getCustomerDAO().getCustomer(id);  
    44.     }  
    45.        @Override  
    46.     public int getNewCustomerId() {  
    47.         return getCustomerDAO().getNewCustomerId();  
    48.     }  
    49.          @Override  
    50.     public List<Customer> getCustomers() {      
    51.         return getCustomerDAO().getCustomers();  
    52.     }  
    53.           
    54.     public ICustomerDAO getCustomerDAO() {  
    55.         return customerDAO;  
    56.     }  
    57.   
    58.     public void setCustomerDAO(ICustomerDAO customerDAO) {  
    59.         this.customerDAO = customerDAO;  
    60.     }  
    61.       
    62. }  
  9. web.xml (Automatically generated and modified later).
     
    Code 
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"   
    3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    4.          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   
    5.          http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">  
    6.     <display-name>Customer Management</display-name>  
    7.   
    8.     <!-- Spring Context Configuration' s Path definition -->  
    9.     <context-param>  
    10.         <param-name>contextConfigLocation</param-name>  
    11.         <param-value>  
    12.             /WEB-INF/applicationContext.xml  
    13.          </param-value>  
    14.     </context-param>  
    15.     <!-- The Bootstrap listener to start up and shut down Spring's root WebApplicationContext.   
    16.         It is registered to Servlet Container -->  
    17.     <listener>  
    18.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    19.     </listener>  
    20.     <listener>  
    21.         <listener-class>  
    22.             org.springframework.web.context.request.RequestContextListener</listener-class>  
    23.     </listener>  
    24.     <!-- Project Stage Level -->  
    25.     <context-param>  
    26.         <param-name>javax.faces.PROJECT_STAGE</param-name>  
    27.         <param-value>Development</param-value>  
    28.     </context-param>  
    29.     <!-- JSF Servlet is defined to container -->  
    30.     <servlet>  
    31.         <servlet-name>Faces Servlet</servlet-name>  
    32.         <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
    33.         <load-on-startup>1</load-on-startup>  
    34.     </servlet>  
    35.     <!-- Mapping with servlet and url for the http requests. -->  
    36.     <servlet-mapping>  
    37.         <servlet-name>Faces Servlet</servlet-name>  
    38.         <url-pattern>*.xhtml</url-pattern>  
    39.     </servlet-mapping>  
    40.     <!-- Welcome Page -->  
    41.     <welcome-file-list>  
    42.         <welcome-file>View/index.xhtml</welcome-file>  
    43.     </welcome-file-list>  
    44. </web-app> 
  10. ApplicationContext.xml (Automatically generated and modified later).
     
    CODE
    1. <?xml version='1.0' encoding='UTF-8' ?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
    4.     xmlns:tx="http://www.springframework.org/schema/tx"  
    5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
    7.         http://www.springframework.org/schema/context  
    8.         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
    9.         http://www.springframework.org/schema/tx  
    10.         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
    11.     <bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    12.     <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
    13.         <property name="url" value="jdbc:mysql://localhost:3306/test" />  
    14.         <property name="username" value="root" />  
    15.         <property name="password" value="" />  
    16.     </bean>  
    17.           
    18.         <!-- Session Factory Declaration -->  
    19.     <bean id="SessionFactory"  
    20.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
    21.         <property name="dataSource" ref="DataSource" />  
    22.         <property name="annotatedClasses">  
    23.             <list>  
    24.                 <value>com.ray.pojo.model.Customer</value>  
    25.             </list>  
    26.         </property>  
    27.         <property name="hibernateProperties">  
    28.             <props>  
    29.     <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
    30.                 <prop key="hibernate.show_sql">true</prop>  
    31.                 <prop key="hibernate.connection.pool_size">10</prop>  
    32.                 <prop key="show_sql">true</prop>  
    33.     <prop key="hibernate.current_session_context_class">thread</prop>  
    34.             </props>  
    35.         </property>  
    36.     </bean>          
    37.     <!-- Enable the configuration of transactional behavior based on annotations -->  
    38.     <tx:annotation-driven transaction-manager="txManager" />  
    39.   
    40.     <!-- Transaction Manager is defined -->     
    41. <bean id="txManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
    42.         <property name="sessionFactory" ref="SessionFactory" />  
    43.     </bean>     
    44.     <context:component-scan base-package="com.ray" />  
    45. </beans>  
  11. faces-config.xml
     
    It is created using notepad. The below-provided code is added to .save as faces-config.xml. Then, copy it and paste to WEB-INF folder.
     
    Code
    1. <?xml version='1.0' encoding='UTF-8'?>  
    2. <faces-config version="2.2"  
    3.               xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
    4.               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    5.               xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   
    6.               http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">  
    7.       
    8.         <!-- JSF and Spring are integrated -->  
    9.     <application>  
    10.         <el-resolver>  
    11.             org.springframework.web.jsf.el.SpringBeanFacesELResolver  
    12.         </el-resolver>  
    13.     </application>      
    14. </faces-config>  
  12. Creating index.xhtml file
     
    index.xhtml code
    1. <?xml version='1.0' encoding='UTF-8' ?>  
    2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
    3.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    4. <html xmlns="http://www.w3.org/1999/xhtml"  
    5.       xmlns:h="http://java.sun.com/jsf/html"  
    6.       xmlns:f="http://java.sun.com/jsf/core"  
    7.       xmlns:ui="http://java.sun.com/jsf/facelets"  
    8.       xmlns:p="http://primefaces.org/ui">  
    9.     <h:head>  
    10.         <title>Customer Manager</title>  
    11.     </h:head>  
    12.     <h:body>  
    13.         <center><h2>Customer Manager</h2></center>  
    14.         <p:dialog id="customerDetail1" widgetVar="$customerDetail1"  
    15.                   header="Add Customer"  
    16.                   hideEffect="explode" appendTo="@(body)"  
    17.                   resizable="false" draggable="false"  
    18.                   closeOnEscape="true">  
    19.             <h:form>  
    20.                  
    21.                 <p:panelGrid columns="2">  
    22.            <h:outputLabel for="customerfirstname" value="Customer FirstName: *" />  
    23.             <p:inputText id="customerfirstname"  
    24.                                      value="#{customerBBean.customer.firstName}"  
    25.                         label="Customer FirstName"  placeholder="Customer FirstName" />  
    26.   
    27.                      
    28.                <h:outputLabel for="customerlastname" value="Customer LastName:"/>  
    29.                     <p:inputText  id="customerlastname" label="Customer LastName" value="#{customerBBean.customer.lastName}" placeholder="Customer LirstName"/>  
    30.                     <h:outputLabel for="sex" value="Choose Sex"/>  
    31.                     <p:selectOneMenu id="sex" label="Choose Sex" value="#{customerBBean.customer.sex}" effect="fold">  
    32.                         <f:selectItem itemLabel="Select One" itemValue="" />  
    33.                         <f:selectItem itemLabel="Male" itemValue="Male"/>  
    34.                         <f:selectItem itemLabel="Female" itemValue="Female"/>  
    35.                     </p:selectOneMenu>  
    36.                     <p:outputLabel for="dob" value="Customer Date of Birth"/>                      
    37.                     <p:calendar id="dob" value="#{customerBBean.customer.dob}" label="DatePosted:"  
    38.       
    39. required="true" pattern="dd/MM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!"         
    40. navigator="true" showButtonPanel="true" yearRange="c-60:c+60" placeholder="Date of Birth" />                       
    41.                     <p:outputLabel for="remark" value="Remark"/>  
    42.                     <p:inputTextarea id="remark" label="Remark" value="#{customerBBean.customer.remark}" placeholder="Remark"/>  
    43.                     <p:commandButton value="add"  process="@form" id="AddButtonId" ajax="true" icon="ui-icon-plus"  
    44.                                      update=":form1:customerTable"        
    45.                                      actionListener="#{customerBBean.addCustomer()}"  
    46.                                    oncomplete="updateTable(),PF('$customerDetail1').hide()" />  
    47.                                       
    48.                    <p:commandButton id="cancelAddButtonId"  value="Cancel"   
    49.                                       onclick="handleComplete(xhr, status, args)"/>  
    50.                 </p:panelGrid>  
    51.             </h:form>  
    52.   
    53.         </p:dialog>  
    54.         <h:outputScript id="handleCompleteScript" target="body">  
    55. /* <![CDATA[ */ 
    56. function handleComplete(xhr, status, args) { 
    57. if(args && args.validName) { 
    58. $userDetail1.hide(); 
    59. } 
    60. } 
    61. /* ]]> */  
    62. </h:outputScript>          
    63.         <p:dialog id="customerDetail2" widgetVar="$customerDetail2"  
    64.                   header="Edit Customer"  
    65.                   hideEffect="explode" appendTo="@(body)"  
    66.                   resizable="false" draggable="false"  
    67.                   closeOnEscape="true">  
    68.             <h:form>                 
    69.                 <p:panelGrid columns="2">  
    70.                     <h:outputLabel for="customerfirstname" value="Customer FirstName: *" />  
    71.             <p:inputText id="customerfirstname"  
    72.                                      value="#{customerBBean.customer.firstName}"  
    73.                          label="Customer FirstName"  placeholder="Customer FirstName" />                     
    74.                <h:outputLabel for="customerlastname" value="Customer LastName:"/>  
    75.                     <p:inputText  id="customerlastname" label="Customer LastName" value="#{customerBBean.customer.lastName}" placeholder="Customer LirstName"/>  
    76.                     <h:outputLabel for="sex" value="Choose Sex"/>  
    77.                     <p:selectOneMenu id="sex" label="Choose Sex" value="#{customerBBean.customer.sex}" effect="fold">  
    78.                         <f:selectItem itemLabel="Select One" itemValue="" />  
    79.                         <f:selectItem itemLabel="Male" itemValue="Male"/>  
    80.                         <f:selectItem itemLabel="Female" itemValue="Female"/>  
    81.                     </p:selectOneMenu>  
    82.                     <p:outputLabel for="dob" value="Customer Date of Birth"/>                      
    83.                     <p:calendar id="dob" value="#{customerBBean.customer.dob}" label="DatePosted:"  
    84.       
    85. required="true" pattern="dd/MM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!"         
    86. navigator="true" showButtonPanel="true" yearRange="c-60:c+60" placeholder="Date of Birth" />                       
    87.                     <p:outputLabel for="remark" value="Remark"/>  
    88.                     <p:inputTextarea id="remark" label="Remark" value="#{customerBBean.customer.remark}" placeholder="Remark"/>  
    89.                     <p:commandButton value="Update"  process="@form" id="EditButtonId" ajax="true" icon="ui-icon-disk"  
    90.                                      update=":form1:customerTable"        
    91.                                      actionListener="#{customerBBean.updateCustomer()}"  
    92.                                     oncomplete="updateTable(),PF('$customerDetail2').hide()" />  
    93.                                       
    94.                    <p:commandButton id="cancelEditButtonId"  value="Cancel"   
    95.                                       onclick="handleComplete(xhr, status, args)"/>  
    96.                 </p:panelGrid>  
    97.             </h:form>  
    98.   
    99.         </p:dialog>  
    100.         <h:outputScript>  
    101.          
    102.   
    103.   
    104. </h:outputScript>          
    105.         <h:outputScript id="handleCompleteScript" target="body">  
    106. /* <![CDATA[ */ 
    107. function handleComplete(xhr, status, args) { 
    108. if(args && args.validName) { 
    109. $userDetail2.hide(); 
    110. } 
    111. } 
    112. /* ]]> */  
    113. </h:outputScript>         
    114.         <h:form id="form1">  
    115.             <p:commandButton icon="ui-icon-plusthick" type="button"  id="addCustomerBtn" value="Add Customer"  
    116.                              update=":customerDetail1" ajax="true"  
    117.                              onclick="PF('$customerDetail1').show()"/>  
    118.              
    119.             <p:commandButton value="Delete" icon="ui-icon-trash"  type="button" onclick="PF('confirmDialog').show()" />   
    120.    <p:confirmDialog message="Are you sure you want to delete this record?Record once deleted can not be retrieved."                          
    121.      header="Deleting" severity="alert" widgetVar="confirmDialog">           
    122.        <p:commandButton  value="Yes Sure" update=":form1:customerTable"   action="#{customerBBean.deleteCustomer()}" oncomplete="PF('confirmDialog').hide()"/>       
    123.           
    124.  <p:commandButton value="Not Yet" onclick="PF('confirmDialog').hide();" type="button" />   
    125.  </p:confirmDialog>              
    126.             <p:spacer> </p:spacer>  
    127.                                  <center><h3>Customers</h3></center>  
    128.               <p:remoteCommand name="updateTable" update="customerTable" />  
    129.   <p:dataTable  value="#{customerBBean.customerList}" var="customer" editable="true" rowKey="#{customer.id}" selection="#{customerBBean.selectedCustomers}" paginator="true" rows="5" id="customerTable">  
    130.      <p:column selectionMode="multiple" headerText="Select" style="width:6%" />  
    131.                 <p:column headerText="Id" style="text-align: left;">  
    132.                     <h:outputText value="#{customer.id}"/>  
    133.                 </p:column>                  
    134.                 <p:column headerText="First Name">  
    135.                         <h:outputText value="#{customer.firstName}"/>  
    136.                     </p:column>  
    137.                     <p:column headerText="Last Name">  
    138.                         <h:outputText value="#{customer.lastName}"/>  
    139.                     </p:column>                 
    140.                 <p:column headerText="Sex">  
    141.                         <h:outputText value="#{customer.sex}"/>  
    142.                     </p:column>  
    143.                     <p:column headerText="Date of Birth" >  
    144.                      <h:outputText value="#{customer.dob}">  
    145.                      <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>  
    146.                          </h:outputText>  
    147.                    </p:column>  
    148.                     <p:column headerText="Remark">  
    149.                         <h:outputText value="#{customer.remark}"/>  
    150.                     </p:column>                       
    151.                 <p:column headerText="Edit" style="text-align: center">  
    152.                    <p:commandButton icon="ui-icon-pencil" id="editCustomerBtn"  
    153.                                      value="Edit" ajax="true"  
    154.                                      actionListener="#{customerBBean.changeCustomer(customer)}"  
    155.                                      update=":customerDetail2"  
    156.                                      oncomplete="PF('$customerDetail2').show()"/>                       
    157.                 </p:column>                                 
    158.                 <p:rowExpansion>  
    159.                     <h:outputText value="#{customer.remark}" styleClass="rowExpansion"/>  
    160.                 </p:rowExpansion>  
    161.             </p:dataTable>  
    162.         </h:form>  
    163.     </h:body>  
    164. </html>  
  13. Add.xhtml code
     
    It is a single page addCustomer and displayCustomers Project. It is an independent file. It can be run by selecting it in Project Explorer and clicking File (from Menu) >> Run 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"  
    3.       xmlns:h="http://java.sun.com/jsf/html"  
    4.       xmlns:f="http://java.sun.com/jsf/core"  
    5.       xmlns:ui="http://java.sun.com/jsf/facelets"  
    6.       xmlns:p="http://primefaces.org/ui">  
    7.     <h:head>  
    8. <title>Welcome to Customer Manager</title>  
    9. </h:head>  
    10. <h:body>  
    11.     <p:messages></p:messages>  
    12.     <h:form id="form1">  
    13.         <table>             
    14.             <tr>  
    15.         <td><h:outputLabel for="firstname" value="FirstName : " /></td>  
    16.                 <td><p:inputText id="firstname"  
    17.                                                  value="#{customerBBean.customer.firstName}">  
    18.                         <f:validateLength minimum="2" />  
    19.                 <p:ajax event="blur" update="firstnameMsg" />  
    20.                     </p:inputText> <p:message id="firstnameMsg" for="firstname" display="icon" /></td>  
    21.             </tr>                        
    22.                         <tr>  
    23.     <td><h:outputLabel for="lastname" value="LastName : " /></td>  
    24.     <td><p:inputText id="lastname"  
    25.                                                  value="#{customerBBean.customer.lastName}">  
    26.                         <f:validateLength minimum="2" />  
    27.             <p:ajax event="blur" update="lastnameMsg" />  
    28.     </p:inputText> <p:message id="lastnameMsg" for="firstname" display="icon" /></td>  
    29.             </tr>                          
    30.                         <tr>  
    31.         <td><h:outputLabel for="sex" value="Choose Sex : " /></td>            
    32.            <td><p:selectOneMenu label="Sex:" value="#{customerBBean.customer.sex}" id="sex">  
    33.                                         <f:selectItem itemLabel="Select One" itemValue="" />  
    34.                                         <f:selectItem itemLabel="Male" itemValue="Male"/>  
    35.                                        <f:selectItem itemLabel="Female" itemValue="Female"/>  
    36.                                        <f:validateLength minimum="2"/>  
    37.                                        <p:ajax event="blur" update="sexMsg" />                                                                                        
    38.              </p:selectOneMenu>  <p:message id="sexMsg" for="sex" display="icon" />    
    39.                                     </td>                        
    40.                                          
    41.             </tr>                          
    42.                         <tr>  
    43.     <td><h:outputLabel for="dob" value="Date of Birth : " /></td>  
    44.                 <td><p> <p:calendar id="dop" value="#{customerBBean.customer.dob}" label="DatePosted:"  
    45.       
    46. required="true" pattern="dd/MMM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!"        
    47. navigator="true" showButtonPanel="true" yearRange="c-60:c+60" /> </p></td>                   
    48.                                  
    49.             </tr>                          
    50.                         <tr>  
    51.             <td><h:outputLabel for="remark" value="Remark : " /></td>  
    52.                 <td><p:inputText id="remark"  
    53.                                                  value="#{customerBBean.customer.remark}">  
    54.                         <f:validateLength minimum="2" />  
    55.                     <p:ajax event="blur" update="remarkMsg" />  
    56. </p:inputText> <p:message id="remarkMsg" for="remark" display="icon" /></td>  
    57.             </tr>  
    58.             <tr>  
    59.                 <td><p:commandButton icon="ui-icon-plusthick" id="addCustomer" value="AddCustomer" type="submit" ajax="true" update=":form1:customertable"  
    60.                                       actionListener="#{customerBBean.addCustomer()}" /></td>                                 
    61.    
    62.                 <td><p:commandButton id="reset" value="Reset"  
    63.                                                      actionListener="#{customerBBean.reset()}" ajax="false" /></td>  
    64.             </tr>  
    65.         </table>  
    66.           
    67.             <center><h3>Customers</h3></center>  
    68.           
    69.                 <p:dataTable id="customertable" var="customer" paginator="true" rows="5" value="#{customerBBean.customerList}"  
    70.             style="width: 100%">  
    71.                                  
    72.                      <p:column headerText="Id">  
    73.                         <h:outputText value="#{customer.id}"/>  
    74.                     </p:column>  
    75.                     <p:column headerText="First Name">  
    76.                         <h:outputText value="#{customer.firstName}"/>  
    77.                     </p:column>  
    78.                     <p:column headerText="Last Name">  
    79.                         <h:outputText value="#{customer.lastName}"/>  
    80.                     </p:column>  
    81.                     <p:column headerText="Sex">  
    82.                         <h:outputText value="#{customer.sex}"/>  
    83.                     </p:column>  
    84.                     <p:column headerText="Date of Birth" >  
    85.                      <h:outputText value="#{customer.dob}">  
    86.                      <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>  
    87.                          </h:outputText>  
    88.                    </p:column>  
    89.                     <p:column headerText="Remark">  
    90.                         <h:outputText value="#{customer.remark}"/>  
    91.                     </p:column>                    
    92.                          
    93.         </p:dataTable>  
    94.     </h:form>  
    95. </h:body>  
    96. </html>  
    Figure: Project Structure
     
    Project Structure
     
    Download the provided downloadable WINRAR file PrimeFacesSpring4Hibernate4CRUDImport.
     
    Open it and read the Readme text file.
     
    Then, import the PrimefacesSpring4Hibernate4CRUD.zip file to NeatBeans8.02.
     
    Create the table Customer if not done already. Then, run the project.
     
    Select the project in the Project Explorer window and run the project.
     
    Index.xhtml page
     
    Index.xhtml page
     
    Add New Customer
     
    Add New Customer
     
    Add New Customer
      
    Edit Existing Customer
     
    Edit Existing Customer
     
    Edit Existing Customer
     
    Delete.xhtml
     
    Delete.xhtml
     
    add.xhtml Page
     
    add.xhtml Page
     


Similar Articles