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.
- JDK8u25
- Netbeans 8.02
- MySQL 5.* Database Server(or XAMPP, for easy MySQL management)
- MySQL Connector 5.*
- Hibernate 4.3.**, Spring4MVC and Primefaces 5.0(Bundled with Netbeans)
Steps:
- Install JDK8 or JDK7, if not installed.
- Install Netbeans and associated ApacheTomcat Server.
- Install MySQL Database Server or XAMPP (for easy management of MySQL).
- After installing Netbeans, click the Services tab on the left.
- Expand the Database node.
- Expand the Drivers node.
- Right-click on MySQL(Connector/Jdriver), then Connect.
- Give the database name as a test.
- As shown below, put the password, if you have given it while installing the MySQL Database Server. However, no password is required for XAMPP.
- Then, Test Connection. If successful, click Finish.
Create a user table by running the below SQL query in the ‘test’ database.
- CREATE TABLE IF NOT EXISTS `customer` (
- `id` int(10) unsigned NOT NULL,
- `FirstName` varchar(45) DEFAULT NULL,
- `LastName` varchar(30) DEFAULT NULL,
- `Sex` varchar(30) DEFAULT NULL,
- `dob` date DEFAULT NULL,
- `Remark` varchar(30) DEFAULT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-
- ALTER TABLE `customer` ADD PRIMARY KEY (`id`);
Insert these records by executing the following
INSERT statement.
- INSERT INTO `customer` (`id`, `FirstName`, `LastName`, `Sex`, `dob`, `Remark`) VALUES
- (1, 'Richard', 'Branson', 'Male', '2001-02-16', 'Good person'),
- (2, 'Raghu', 'sahu', 'Male', '2003-07-09', 'good person'),
- (3, 'Sujata', 'Mishra', 'Female', '1969-07-16', 'Good Person'),
- (4, 'Simadri', 'Dhal', 'Male', '2003-07-01', 'Good Person'),
- (5, 'Aradhana', 'Ray', 'Female', '2002-09-02', 'Naughty Girl'),
- (6, 'Sibananda', 'Ray', 'Male', '1972-07-17', 'Good Person'),
- (7, 'SWATI', 'MISHRA', 'Female', '2003-03-18', 'GOOD GIRL'),
- (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.
- aopalliance-1.0.jar
- javax.inject-1.jar
- commons-logging-1.2.jar
- 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.
In the above figure, Database Connection should be with the ‘test’ database.
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
Creating Packages and Classes
Right-click on
Source Package folder and create four packages.
- com.ray.bean.controller-->This would contain JSF managed bean class CustomerBBean.java
- com.ray.dao-This would contain DAO (Data Access Object) class and interface CustomerDAO.java and ICustomerDAO.java.
- com.ray.pojo.model-This would contain entity (POJO) class Customer.java. POJO Stands for Plain Old Java Objects.
- 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.
- hibernate.cfg,xml file is automatically generated. (It will be used to create Customer.java and deleted.)
- Reverse Engineering File hibernate.reveng.xml. (It will be used to create Customer.java and deleted.)
- Entity (POJO) File Customer.java(POJO stands for Plain Old Java Objects)
- JSF managed bean file CustomerBBean.java
- DataAccessObject(DAO) file ICustomerDao.java
- DataAccessObject(DAO) file CustomerDao.java
- SpringService file ICustomerService.java
- SpringService file CustomerService.java
- Index.xhtml Adds new Customer, edit Customer, delete Customer and displays all Customers' information
- 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.
- faces-config.xml It is to be added after creating under WEB-INF folder.
- web.xml (Automatically generated).
- 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.
- 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
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="hibernate.connection.url">jdbc:mysql:
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password"> </property>
- <property name="hibernate.connection.pool_size">10</property>
- <property name="show_sql">true</property>
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="hibernate.hbm2ddl.auto">update</property>
- <mapping class="com.ray.pojo.model.Customer"/>
- </session-factory>
- </hibernate-configuration>
- Creating Reverse Engineering File - hibernate.reveng.xml (It would be deleted after it is used for creating Customer.java entity class).
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
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
- <hibernate-reverse-engineering>
- <schema-selection match-catalog="test"/>
- <table-filter match-name="customer"/>
- </hibernate-reverse-engineering>
- 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.
Customer.java CODE
- package com.ray.pojo.model;
-
- import java.util.Date;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
-
-
-
-
- @Entity
- @Table(name="customer"
- ,catalog="test"
- )
- public class Customer implements java.io.Serializable {
- private int id;
- private String firstName;
- private String lastName;
- private String sex;
- private Date dob;
- private String remark;
-
- public Customer() {
- }
- public Customer(int id) {
- this.id = id;
- }
- public Customer(int id, String firstName, String lastName, String sex, Date dob, String remark) {
- this.id = id;
- this.firstName = firstName;
- this.lastName = lastName;
- this.sex = sex;
- this.dob = dob;
- this.remark = remark;
- }
- @Id
- @Column(name="id", unique=true, nullable=false)
- public int getId() {
- return this.id;
- }
- public void setId(int id) {
- this.id = id;
- }
- @Column(name="FirstName", length=45)
- public String getFirstName() {
- return this.firstName;
- }
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
- @Column(name="LastName", length=30)
- public String getLastName() {
- return this.lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- @Column(name="Sex", length=30)
- public String getSex() {
- return this.sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- @Temporal(TemporalType.DATE)
- @Column(name="dob", length=10)
- public Date getDob() {
- return this.dob;
- }
- public void setDob(Date dob) {
- this.dob = dob;
- }
- @Column(name="Remark", length=30)
- public String getRemark() {
- return this.remark;
- }
- public void setRemark(String remark) {
- this.remark = remark;
- }
- public void reset() {
- this.setId(0);
- this.setFirstName("");
- this.setLastName("");
- this.setSex("");
- this.setDob(null);
- this.setRemark("");
- }
-
-
- @Override
- public String toString() {
- return "customer"
- + "\n\t Id: " + this.id
- + "\n\t FirstName: " + this.firstName
- + "\n\t LastNmae: " + this.lastName
- + "\n\t Sex: " + this.sex
- + "\n\t Date of Birth: " + this.dob
- + "\n\t Remark: " + this.remark;
- }
- }
- 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
- package com.ray.bean.controller;
- import java.io.Serializable;
- import java.util.ArrayList;
- import java.util.List;
- import javax.faces.application.FacesMessage;
- import javax.faces.context.FacesContext;
- import javax.inject.Inject;
- import javax.inject.Named;
- import org.springframework.context.annotation.Scope;
- import org.springframework.dao.DataAccessException;
- import com.ray.pojo.model.Customer;
- import com.ray.spring.service.ICustomerService;
- import java.util.Date;
- import org.primefaces.context.RequestContext;
-
-
-
-
-
- @Named("customerBBean")
- @Scope("session")
- public class CustomerBBean implements Serializable {
-
- private static final long serialVersionUID = 1L;
- @Inject
- private ICustomerService customerService;
- private List<Customer> customerList;
- private Customer customer = new Customer();
- private List<Customer> selectedCustomers;
- private Customer selectedCustomer;
-
-
-
-
- public CustomerBBean() {
- }
-
- public void addCustomer() {
- try {
-
- int newId = getCustomerService().getNewCustomerId();
- customer.setId(newId);
- getCustomerService().addCustomer(customer);
- this.reset();
- RequestContext.getCurrentInstance().update("customerTable");
- FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save ","Customer Information saved successfully.");
- RequestContext.getCurrentInstance().showMessageInDialog(message);
- FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Added!", "Message: "));
-
- } catch (DataAccessException e) {
- e.printStackTrace();
- FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "D'oh!", "Message: "));
- }
- }
- public void changeCustomer(Customer customer) {
- this.customer= customer;
-
- }
-
- public void updateCustomer(){
- String FirstName = customer.getFirstName();
- FacesMessage message1= new FacesMessage(FacesMessage.SEVERITY_INFO, "FirstName",FirstName);
- RequestContext.getCurrentInstance().showMessageInDialog(message1);
- getCustomerService().updateCustomer(customer);
- System.out.println("Customer Info successfully saved.");
- FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save","Customer Information updated successfully .");
- RequestContext.getCurrentInstance().showMessageInDialog(message);
- this.reset();
- }
-
- public void deleteCustomer(){
-
-
- getCustomerService().deleteCustomer(selectedCustomers);
- FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Customer Record deleted successfully");
- RequestContext.getCurrentInstance().showMessageInDialog(message);
- RequestContext.getCurrentInstance().update("customerTable");
- }
- public void reset() {
- this.customer.setId(0);
- this.customer.setFirstName("");
- this.customer.setLastName("");
- this.customer.setSex("");
- this.customer.setDob(null);
- this.customer.setRemark("");
- }
- public List<Customer> getCustomerList() {
- customerList = new ArrayList<Customer>();
- customerList.addAll(getCustomerService().getCustomers());
- return customerList;
- }
- public ICustomerService getCustomerService() {
- return customerService;
- }
- public void setCustomerService(ICustomerService customerService) {
- this.customerService = customerService;
- }
-
-
- public void setCustomerList(List<Customer> customerList) {
- this.customerList = customerList;
- }
- public Customer getCustomer() {
- return customer;
- }
- public void setCustomer(Customer customer) {
- this.customer = customer;
- }
- public List<Customer> getSelectedCustomers() {
- return selectedCustomers;
- }
- public void setSelectedCustomers(List<Customer> selectedCustomers) {
- this.selectedCustomers = selectedCustomers;
- }
- public Customer getSelectedCustomer() {
- return selectedCustomer;
- }
- public void setSelectedCustomer(Customer selectedCustomer) {
- this.selectedCustomer = selectedCustomer;
- }
-
- }
- 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
- package com.ray.dao;
- import java.util.List;
- import com.ray.pojo.model.Customer;
-
-
-
-
- public interface ICustomerDAO {
- public void addCustomer(Customer customer);
- public void updateCustomer(Customer customer);
- public int getNewCustomerId();
- public Customer getCustomer(int id);
- public List<Customer> getCustomers();
- public void deleteCustomer(List<Customer> customer);
- }
- 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
- package com.ray.dao;
-
- import java.util.List;
- import java.util.Iterator;
- import javax.inject.Inject;
- import javax.inject.Named;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import com.ray.dao.ICustomerDAO;
- import com.ray.pojo.model.Customer;
-
-
-
-
- @Named
- public class CustomerDAO implements ICustomerDAO{
-
- @Inject
- private SessionFactory sessionFactory;
- public SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- @Override
- public void addCustomer(Customer customer) {
- int id = customer.getId();
- System.out.println("New DAO Customer Id:-"+id);
- String firstname = customer.getFirstName();
- System.out.println(firstname);
- Session session = getSessionFactory().getCurrentSession();
- Transaction trans = session.beginTransaction();
- session.persist(customer);
- trans.commit();
- }
- @Override
- public void updateCustomer(Customer customer) {
- Session session = getSessionFactory().getCurrentSession();
- Transaction trans = session.beginTransaction();
- session.update(customer);
- trans.commit();
- }
- @Override
- public Customer getCustomer(int id) {
- Session session = getSessionFactory().getCurrentSession();
- Transaction trans = session.beginTransaction();
-
- List<?> list = session
- .createQuery("from Customer where id=?").setParameter(0, id)
- .list();
- trans.commit();
- return (Customer) list.get(0);
- }
-
-
-
- @Override
- public int getNewCustomerId() {
- Session session = sessionFactory.getCurrentSession();
- Transaction trans = session.beginTransaction();
- String query = "SELECT max(c.id) FROM Customer c";
- List list = session.createQuery(query).list();
- int maxId = ((Integer) list.get(0)).intValue();
- trans.commit();
- return (maxId+1) ;
- }
- @SuppressWarnings("unchecked")
- @Override
- public List<Customer> getCustomers() {
- Session session = getSessionFactory().getCurrentSession();
- Transaction trans = session.beginTransaction();
- List<Customer> list = session.createQuery("from Customer").list();
- trans.commit();
- return list;
- }
-
- @Override
- public void deleteCustomer(List<Customer> customers) {
- Session session = sessionFactory.openSession();
- Transaction tx = null;
- try {
- tx = session.beginTransaction();
- for (Iterator iterator = customers.iterator(); iterator.hasNext();) {
- Customer customer = (Customer) iterator.next();
- session.delete(customer);
- }
-
- tx.commit();
- } catch (HibernateException e) {
- if (tx != null)
- tx.rollback();
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- }
- 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
- package com.ray.spring.service;
- import java.util.List;
- import com.ray.pojo.model.Customer;
-
-
-
-
- public interface ICustomerService {
- public void addCustomer(Customer customer);
- public void updateCustomer(Customer customer);
- public int getNewCustomerId();
- public Customer getCustomerById(int id);
- public List<Customer> getCustomers();
- public void deleteCustomer(List<Customer> customers);
-
- }
- 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
- package com.ray.spring.service;
-
- import java.util.List;
- import javax.inject.Inject;
- import javax.inject.Named;
- import org.springframework.transaction.annotation.Transactional;
- import com.ray.pojo.model.Customer;
- import com.ray.dao.ICustomerDAO;
- import com.ray.spring.service.ICustomerService;
-
-
-
-
-
-
- @Named
- @Transactional(readOnly = true)
- public class CustomerService implements ICustomerService{
- @Inject
- ICustomerDAO customerDAO;
- @Transactional(readOnly = false)
- @Override
- public void addCustomer(Customer customer) {
- getCustomerDAO().addCustomer(customer);
- }
-
- @Transactional(readOnly = false)
- @Override
- public void deleteCustomer(List<Customer> customers) {
-
- getCustomerDAO().deleteCustomer(customers);
- }
-
- @Transactional(readOnly = false)
- @Override
- public void updateCustomer(Customer customer) {
- getCustomerDAO().updateCustomer(customer);
- }
-
-
- @Override
- public Customer getCustomerById(int id) {
- return getCustomerDAO().getCustomer(id);
- }
- @Override
- public int getNewCustomerId() {
- return getCustomerDAO().getNewCustomerId();
- }
- @Override
- public List<Customer> getCustomers() {
- return getCustomerDAO().getCustomers();
- }
-
- public ICustomerDAO getCustomerDAO() {
- return customerDAO;
- }
-
- public void setCustomerDAO(ICustomerDAO customerDAO) {
- this.customerDAO = customerDAO;
- }
-
- }
- web.xml (Automatically generated and modified later).
Code
- <?xml version="1.0" encoding="UTF-8"?>
- <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:
- http:
- <display-name>Customer Management</display-name>
-
- <!-- Spring Context Configuration' s Path definition -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/applicationContext.xml
- </param-value>
- </context-param>
- <!-- The Bootstrap listener to start up and shut down Spring's root WebApplicationContext.
- It is registered to Servlet Container -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <listener>
- <listener-class>
- org.springframework.web.context.request.RequestContextListener</listener-class>
- </listener>
- <!-- Project Stage Level -->
- <context-param>
- <param-name>javax.faces.PROJECT_STAGE</param-name>
- <param-value>Development</param-value>
- </context-param>
- <!-- JSF Servlet is defined to container -->
- <servlet>
- <servlet-name>Faces Servlet</servlet-name>
- <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <!-- Mapping with servlet and url for the http requests. -->
- <servlet-mapping>
- <servlet-name>Faces Servlet</servlet-name>
- <url-pattern>*.xhtml</url-pattern>
- </servlet-mapping>
- <!-- Welcome Page -->
- <welcome-file-list>
- <welcome-file>View/index.xhtml</welcome-file>
- </welcome-file-list>
- </web-app>
- ApplicationContext.xml (Automatically generated and modified later).
CODE
- <?xml version='1.0' encoding='UTF-8' ?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http:
- http:
- http:
- http:
- http:
- http:
- <bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="" />
- </bean>
-
- <!-- Session Factory Declaration -->
- <bean id="SessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource" ref="DataSource" />
- <property name="annotatedClasses">
- <list>
- <value>com.ray.pojo.model.Customer</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- <prop key="hibernate.show_sql">true</prop>
- <prop key="hibernate.connection.pool_size">10</prop>
- <prop key="show_sql">true</prop>
- <prop key="hibernate.current_session_context_class">thread</prop>
- </props>
- </property>
- </bean>
- <!-- Enable the configuration of transactional behavior based on annotations -->
- <tx:annotation-driven transaction-manager="txManager" />
-
- <!-- Transaction Manager is defined -->
- <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="SessionFactory" />
- </bean>
- <context:component-scan base-package="com.ray" />
- </beans>
- 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
- <?xml version='1.0' encoding='UTF-8'?>
- <faces-config version="2.2"
- xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http:
- http:
-
- <!-- JSF and Spring are integrated -->
- <application>
- <el-resolver>
- org.springframework.web.jsf.el.SpringBeanFacesELResolver
- </el-resolver>
- </application>
- </faces-config>
- Creating index.xhtml file
index.xhtml code
- <?xml version='1.0' encoding='UTF-8' ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml"
- xmlns:h="http://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">
- <h:head>
- <title>Customer Manager</title>
- </h:head>
- <h:body>
- <center><h2>Customer Manager</h2></center>
- <p:dialog id="customerDetail1" widgetVar="$customerDetail1"
- header="Add Customer"
- hideEffect="explode" appendTo="@(body)"
- resizable="false" draggable="false"
- closeOnEscape="true">
- <h:form>
-
- <p:panelGrid columns="2">
- <h:outputLabel for="customerfirstname" value="Customer FirstName: *" />
- <p:inputText id="customerfirstname"
- value="#{customerBBean.customer.firstName}"
- label="Customer FirstName" placeholder="Customer FirstName" />
-
-
- <h:outputLabel for="customerlastname" value="Customer LastName:"/>
- <p:inputText id="customerlastname" label="Customer LastName" value="#{customerBBean.customer.lastName}" placeholder="Customer LirstName"/>
- <h:outputLabel for="sex" value="Choose Sex"/>
- <p:selectOneMenu id="sex" label="Choose Sex" value="#{customerBBean.customer.sex}" effect="fold">
- <f:selectItem itemLabel="Select One" itemValue="" />
- <f:selectItem itemLabel="Male" itemValue="Male"/>
- <f:selectItem itemLabel="Female" itemValue="Female"/>
- </p:selectOneMenu>
- <p:outputLabel for="dob" value="Customer Date of Birth"/>
- <p:calendar id="dob" value="#{customerBBean.customer.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" />
- <p:outputLabel for="remark" value="Remark"/>
- <p:inputTextarea id="remark" label="Remark" value="#{customerBBean.customer.remark}" placeholder="Remark"/>
- <p:commandButton value="add" process="@form" id="AddButtonId" ajax="true" icon="ui-icon-plus"
- update=":form1:customerTable"
- actionListener="#{customerBBean.addCustomer()}"
- oncomplete="updateTable(),PF('$customerDetail1').hide()" />
-
- <p:commandButton id="cancelAddButtonId" value="Cancel"
- onclick="handleComplete(xhr, status, args)"/>
- </p:panelGrid>
- </h:form>
-
- </p:dialog>
- <h:outputScript id="handleCompleteScript" target="body">
- /* <![CDATA[ */
- function handleComplete(xhr, status, args) {
- if(args && args.validName) {
- $userDetail1.hide();
- }
- }
- /* ]]> */
- </h:outputScript>
- <p:dialog id="customerDetail2" widgetVar="$customerDetail2"
- header="Edit Customer"
- hideEffect="explode" appendTo="@(body)"
- resizable="false" draggable="false"
- closeOnEscape="true">
- <h:form>
- <p:panelGrid columns="2">
- <h:outputLabel for="customerfirstname" value="Customer FirstName: *" />
- <p:inputText id="customerfirstname"
- value="#{customerBBean.customer.firstName}"
- label="Customer FirstName" placeholder="Customer FirstName" />
- <h:outputLabel for="customerlastname" value="Customer LastName:"/>
- <p:inputText id="customerlastname" label="Customer LastName" value="#{customerBBean.customer.lastName}" placeholder="Customer LirstName"/>
- <h:outputLabel for="sex" value="Choose Sex"/>
- <p:selectOneMenu id="sex" label="Choose Sex" value="#{customerBBean.customer.sex}" effect="fold">
- <f:selectItem itemLabel="Select One" itemValue="" />
- <f:selectItem itemLabel="Male" itemValue="Male"/>
- <f:selectItem itemLabel="Female" itemValue="Female"/>
- </p:selectOneMenu>
- <p:outputLabel for="dob" value="Customer Date of Birth"/>
- <p:calendar id="dob" value="#{customerBBean.customer.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" />
- <p:outputLabel for="remark" value="Remark"/>
- <p:inputTextarea id="remark" label="Remark" value="#{customerBBean.customer.remark}" placeholder="Remark"/>
- <p:commandButton value="Update" process="@form" id="EditButtonId" ajax="true" icon="ui-icon-disk"
- update=":form1:customerTable"
- actionListener="#{customerBBean.updateCustomer()}"
- oncomplete="updateTable(),PF('$customerDetail2').hide()" />
-
- <p:commandButton id="cancelEditButtonId" value="Cancel"
- onclick="handleComplete(xhr, status, args)"/>
- </p:panelGrid>
- </h:form>
-
- </p:dialog>
- <h:outputScript>
-
-
-
- </h:outputScript>
- <h:outputScript id="handleCompleteScript" target="body">
- /* <![CDATA[ */
- function handleComplete(xhr, status, args) {
- if(args && args.validName) {
- $userDetail2.hide();
- }
- }
- /* ]]> */
- </h:outputScript>
- <h:form id="form1">
- <p:commandButton icon="ui-icon-plusthick" type="button" id="addCustomerBtn" value="Add Customer"
- update=":customerDetail1" ajax="true"
- onclick="PF('$customerDetail1').show()"/>
-
- <p:commandButton value="Delete" icon="ui-icon-trash" type="button" onclick="PF('confirmDialog').show()" />
- <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">
- <p:commandButton value="Yes Sure" update=":form1:customerTable" action="#{customerBBean.deleteCustomer()}" oncomplete="PF('confirmDialog').hide()"/>
-
- <p:commandButton value="Not Yet" onclick="PF('confirmDialog').hide();" type="button" />
- </p:confirmDialog>
- <p:spacer> </p:spacer>
- <center><h3>Customers</h3></center>
- <p:remoteCommand name="updateTable" update="customerTable" />
- <p:dataTable value="#{customerBBean.customerList}" var="customer" editable="true" rowKey="#{customer.id}" selection="#{customerBBean.selectedCustomers}" paginator="true" rows="5" id="customerTable">
- <p:column selectionMode="multiple" headerText="Select" style="width:6%" />
- <p:column headerText="Id" style="text-align: left;">
- <h:outputText value="#{customer.id}"/>
- </p:column>
- <p:column headerText="First Name">
- <h:outputText value="#{customer.firstName}"/>
- </p:column>
- <p:column headerText="Last Name">
- <h:outputText value="#{customer.lastName}"/>
- </p:column>
- <p:column headerText="Sex">
- <h:outputText value="#{customer.sex}"/>
- </p:column>
- <p:column headerText="Date of Birth" >
- <h:outputText value="#{customer.dob}">
- <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
- </h:outputText>
- </p:column>
- <p:column headerText="Remark">
- <h:outputText value="#{customer.remark}"/>
- </p:column>
- <p:column headerText="Edit" style="text-align: center">
- <p:commandButton icon="ui-icon-pencil" id="editCustomerBtn"
- value="Edit" ajax="true"
- actionListener="#{customerBBean.changeCustomer(customer)}"
- update=":customerDetail2"
- oncomplete="PF('$customerDetail2').show()"/>
- </p:column>
- <p:rowExpansion>
- <h:outputText value="#{customer.remark}" styleClass="rowExpansion"/>
- </p:rowExpansion>
- </p:dataTable>
- </h:form>
- </h:body>
- </html>
- 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.
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <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">
- <h:head>
- <title>Welcome to Customer Manager</title>
- </h:head>
- <h:body>
- <p:messages></p:messages>
- <h:form id="form1">
- <table>
- <tr>
- <td><h:outputLabel for="firstname" value="FirstName : " /></td>
- <td><p:inputText id="firstname"
- value="#{customerBBean.customer.firstName}">
- <f:validateLength minimum="2" />
- <p:ajax event="blur" update="firstnameMsg" />
- </p:inputText> <p:message id="firstnameMsg" for="firstname" display="icon" /></td>
- </tr>
- <tr>
- <td><h:outputLabel for="lastname" value="LastName : " /></td>
- <td><p:inputText id="lastname"
- value="#{customerBBean.customer.lastName}">
- <f:validateLength minimum="2" />
- <p:ajax event="blur" update="lastnameMsg" />
- </p:inputText> <p:message id="lastnameMsg" for="firstname" display="icon" /></td>
- </tr>
- <tr>
- <td><h:outputLabel for="sex" value="Choose Sex : " /></td>
- <td><p:selectOneMenu label="Sex:" value="#{customerBBean.customer.sex}" id="sex">
- <f:selectItem itemLabel="Select One" itemValue="" />
- <f:selectItem itemLabel="Male" itemValue="Male"/>
- <f:selectItem itemLabel="Female" itemValue="Female"/>
- <f:validateLength minimum="2"/>
- <p:ajax event="blur" update="sexMsg" />
- </p:selectOneMenu> <p:message id="sexMsg" for="sex" display="icon" />
- </td>
-
- </tr>
- <tr>
- <td><h:outputLabel for="dob" value="Date of Birth : " /></td>
- <td><p> <p:calendar id="dop" value="#{customerBBean.customer.dob}" label="DatePosted:"
-
- required="true" pattern="dd/MMM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Birth!"
- navigator="true" showButtonPanel="true" yearRange="c-60:c+60" /> </p></td>
-
- </tr>
- <tr>
- <td><h:outputLabel for="remark" value="Remark : " /></td>
- <td><p:inputText id="remark"
- value="#{customerBBean.customer.remark}">
- <f:validateLength minimum="2" />
- <p:ajax event="blur" update="remarkMsg" />
- </p:inputText> <p:message id="remarkMsg" for="remark" display="icon" /></td>
- </tr>
- <tr>
- <td><p:commandButton icon="ui-icon-plusthick" id="addCustomer" value="AddCustomer" type="submit" ajax="true" update=":form1:customertable"
- actionListener="#{customerBBean.addCustomer()}" /></td>
-
- <td><p:commandButton id="reset" value="Reset"
- actionListener="#{customerBBean.reset()}" ajax="false" /></td>
- </tr>
- </table>
-
- <center><h3>Customers</h3></center>
-
- <p:dataTable id="customertable" var="customer" paginator="true" rows="5" value="#{customerBBean.customerList}"
- style="width: 100%">
-
- <p:column headerText="Id">
- <h:outputText value="#{customer.id}"/>
- </p:column>
- <p:column headerText="First Name">
- <h:outputText value="#{customer.firstName}"/>
- </p:column>
- <p:column headerText="Last Name">
- <h:outputText value="#{customer.lastName}"/>
- </p:column>
- <p:column headerText="Sex">
- <h:outputText value="#{customer.sex}"/>
- </p:column>
- <p:column headerText="Date of Birth" >
- <h:outputText value="#{customer.dob}">
- <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
- </h:outputText>
- </p:column>
- <p:column headerText="Remark">
- <h:outputText value="#{customer.remark}"/>
- </p:column>
-
- </p:dataTable>
- </h:form>
- </h:body>
- </html>
Figure: 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
Add New Customer
Edit Existing Customer
Delete.xhtml
add.xhtml Page