This tutorial is continuation to my first tutorial on primefaces. i.e, PrimeFaces Hello world example. Before digging more about Primefaces components and its features, let’s have a good project template solution for doing all the CRUD operations by integrating Primefaces with Spring and Hibernate framework’s.
This combination is recommended because SpringSource suggests PrimeFaces to be used in JSF-Spring applications. Also Spring ROO only supports PrimeFaces as JSF addon. That is great news for the Spring developers.
So let’s take PrimeFaces as a UI framework, Spring in Business layer and Hibernate as Data Access layer.The beauty of this combination is, that there are very minimal configurations through xml and by annotations gives more flexibility to developers just to concentrate on the UI and business.
– See more at: https://javabeat.net/primefaces-spring-data-neo4j-integration/#sthash.1X4vJqoA.dpuf
Now we see how Spring and hibernate configuration will looks and then we will go ahead with the implementation steps.
1. Create Table in DB
Create a table with basic columns like id,name and surname. I took example as Customer.
CREATE TABLE CUSTOMER ( id int(11) NOT NULL, name varchar(45) NOT NULL, surname varchar(45) NOT NULL, PRIMARY KEY (‘id’) );
2. Create a Maven Project with Primefaces,Spring and Hiberante Dependecnies
Open your IDE and start creating a Maven project. Folder structure for that project will looks like this,
3. Update POM with all the Dependencies
Place all Spring, JSF, Hibernate, Primefaces, DB Driver and C3p0 dependencies in Maven’s pom.xml. In this example I choose DB2 as my DB driver.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat</groupId> <artifactId>primefacesSpring</artifactId> <packaging>war</packaging> <version>1.0</version> <name>primefaces Spring Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>3.2.5.RELEASE</spring.version> </properties> <repositories> <repository> <id>prime-repo</id> <name>Prime Repo</name> <url>http://repository.primefaces.org</url> </repository> <repository> <id>spring-milestone</id> <url>http://repo.spring.io/libs-milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencies> <!-- PrimeFaces --> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>4.0</version> </dependency> <!-- JSF --> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.11</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.11</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <!-- EL --> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate dependencies --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.0.Final</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> <!-- c3p0 dependency --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>net.sf.jt400</groupId> <artifactId>jt400-full</artifactId> <version>5.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
4. Create Web.xml
Following is the deployment descriptor file (web.xml). In this, we specifically configure listeners for the Spring context loading and also configuring Faces Servlet.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>PrimeFaces Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <!-- Change to "Production" when you are ready to deploy --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <!-- Welcome page --> <welcome-file-list> <welcome-file>faces/index.xhtml</welcome-file> </welcome-file-list> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map these files with JSF --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>
5. Create Spring Configuration File
Spring Application Context’ s content is shown as follows. In this file, we mainly configure our datasource, hibernate session factory using C3P0 connection pooling and all remaining spring parameters.
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:component-scan base-package="net.javabeat.spring"/> <context:annotation-config/> <context:spring-configured/> <!-- Data Source Declaration --> <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.ibm.as400.access.AS400JDBCDriver" /> <property name="jdbcUrl" value="jdbc:as400://172.18.10.112:446/Takaful" /> <property name="user" value="tmdittis" /> <property name="password" value="tmdittis" /> <property name="maxPoolSize" value="2" /> <property name="maxStatements" value="0" /> <property name="minPoolSize" value="1" /> </bean> <!-- Session Factory Declaration --> <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="DataSource" /> <!-- <property name="packagesToScan"> <list> <value>net.javabeat.spring.model</value> </list> </property>--> <property name="annotatedClasses"> <list> <value>net.javabeat.spring.model.Customer</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.DB2400Dialect</prop> <prop key="hibernate.show_sql">true</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> </beans>
6. Create faces-config.xml
This is the last xml file, we configure for this application and it is mainly intended for making integration between Primefaces managed beans and Spring with SpringBeanFacesELResolver. (Read : Introduction to JSF).
<?xml version="1.0" encoding="utf-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application> </faces-config>
7. Create Entity and Assign it to Session factory
Now it’s time to create Java classes. At first, we will create the model class for Customer table and we will name it as “Customer” (Entity).
package net.javabeat.spring.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * * Customer Entity * * @author uday * @since 19 Nov 2013 * @version 1.0.0 * */ @Entity @Table(name="CUSTOMER") public class Customer { private int id; private String name; private String surname; /** * Get Customer Id * * @return int - Customer Id */ @Id @Column(name="ID", unique = true, nullable = false) public int getId() { return id; } /** * Set Customer Id * * @param id int - Customer Id */ public void setId(int id) { this.id = id; } /** * Get Customer Name * * @return String - Customer Name */ @Column(name="NAME", unique = true, nullable = false) public String getName() { return name; } /** * Set Customer Name * * @param name String - Customer Name */ public void setName(String name) { this.name = name; } /** * Get Customer Surname * * @return String - Customer Surname */ @Column(name="SURNAME", unique = true, nullable = false) public String getSurname() { return surname; } /** * Set Customer Surname * * @param surname String - Customer Surname */ public void setSurname(String surname) { this.surname = surname; } @Override public String toString() { StringBuffer strBuff = new StringBuffer(); strBuff.append("id : ").append(getId()); strBuff.append(", name : ").append(getName()); strBuff.append(", surname : ").append(getSurname()); return strBuff.toString(); } }
8. CREATE DAO Class
CustomerDAO provides methods of Data Access Layer using @Repository annotation. The data access layer manages all the logic to persist and retrieve the data from database using hibernate sessionfactory.
package net.javabeat.spring.dao; import java.util.List; import net.javabeat.spring.model.Customer; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * * customer DAO * * @author uday * @since 19 Nov 2013 * @version 1.0.0 * */ @Repository public class CustomerDAO { @Autowired private SessionFactory sessionFactory; /** * Get Hibernate Session Factory * * @return SessionFactory - Hibernate Session Factory */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * Set Hibernate Session Factory * * @param sessionFactory SessionFactory - Hibernate Session Factory */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * Add customer * * @param customer customer */ public void addCustomer(Customer customer) { getSessionFactory().getCurrentSession().save(customer); } /** * Delete customer * * @param customer customer */ public void deleteCustomer(Customer customer) { getSessionFactory().getCurrentSession().delete(customer); } /** * Update customer * * @param customer customer */ public void updateCustomer(Customer customer) { getSessionFactory().getCurrentSession().update(customer); } /** * Get customer * * @param id int * @return customer */ public Customer getCustomerById(int id) { List list = getSessionFactory().getCurrentSession() .createQuery("from Customer where id=?") .setParameter(0, id).list(); return (Customer)list.get(0); } /** * Get customer List * * @return List - customer list */ public List<Customer> getCustomers() { List list = getSessionFactory().getCurrentSession().createQuery("from Customer").list(); return list; } }
9. CREATE Serivce Class
CustomerService class provides methods to process the business logic using @Service annotation.
package net.javabeat.spring.service; import java.util.List; import net.javabeat.spring.dao.CustomerDAO; import net.javabeat.spring.model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * * Customer Service * * @author uday * @since 19 Nov 2013 * @version 1.0.0 * * */ @Service("CustomerService") @Transactional(readOnly = true) public class CustomerService { // CustomerDAO is injected... @Autowired CustomerDAO customerDAO; /** * Add Customer * * @param customer Customer */ @Transactional(readOnly = false) public void addCustomer(Customer customer) { getCustomerDAO().addCustomer(customer); } /** * Delete Customer * * @param customer Customer */ @Transactional(readOnly = false) public void deleteCustomer(Customer customer) { getCustomerDAO().deleteCustomer(customer); } /** * Update Customer * * @param customer Customer */ @Transactional(readOnly = false) public void updateCustomer(Customer customer) { getCustomerDAO().updateCustomer(customer); } /** * Get Customer * * @param id int Customer Id */ public Customer getCustomerById(int id) { return getCustomerDAO().getCustomerById(id); } /** * Get Customer List * */ public List<Customer> getCustomers() { return getCustomerDAO().getCustomers(); } /** * Get Customer DAO * * @return customerDAO - Customer DAO */ public CustomerDAO getCustomerDAO() { return customerDAO; } /** * Set Customer DAO * * @param customerDAO - CustomerDAO */ public void setCustomerDAO(CustomerDAO customerDAO) { this.customerDAO = customerDAO; } }
10. Create Managed Bean
In the end, create JSF managed bean.
package net.javabeat.managedController; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import net.javabeat.spring.model.Customer; import net.javabeat.spring.service.CustomerService; import org.springframework.dao.DataAccessException; /** * * Customer Managed Bean * * @author uday * @since 19 Nov 2013 * @version 1.0.0 * */ @ManagedBean(name="customerMB") @RequestScoped public class CustomerManagedBean implements Serializable { private static final long serialVersionUID = 1L; private static final String SUCCESS = "success"; private static final String ERROR = "error"; //Spring Customer Service is injected... @ManagedProperty(value="#{CustomerService}") CustomerService customerService; List<Customer> customerList; private int id; private String name; private String surname; /** * Add Customer * * @return String - Response Message */ public String addCustomer() { try { Customer customer = new Customer(); customer.setId(getId()); customer.setName(getName()); customer.setSurname(getSurname()); getCustomerService().addCustomer(customer); return SUCCESS; } catch (DataAccessException e) { e.printStackTrace(); } return ERROR; } /** * Reset Fields * */ public void reset() { this.setId(0); this.setName(""); this.setSurname(""); } /** * Get Customer List * * @return List - Customer List */ public List<Customer> getCustomerList() { customerList = new ArrayList<Customer>(); customerList.addAll(getCustomerService().getCustomers()); return customerList; } /** * Get Customer Service * * @return ICustomerService - Customer Service */ public CustomerService getCustomerService() { return customerService; } /** * Set Customer Service * * @param customerService ICustomerService - Customer Service */ public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * Set Customer List * * @param customerList List - Customer List */ public void setCustomerList(List<Customer> customerList) { this.customerList = customerList; } /** * Get Customer Id * * @return int - Customer Id */ public int getId() { return id; } /** * Set Customer Id * * @param id int - Customer Id */ public void setId(int id) { this.id = id; } /** * Get Customer Name * * @return String - Customer Name */ public String getName() { return name; } /** * Set Customer Name * * @param name String - Customer Name */ public void setName(String name) { this.name = name; } /** * Get Customer Surname * * @return String - Customer Surname */ public String getSurname() { return surname; } /** * Set Customer Surname * * @param surname String - Customer Surname */ public void setSurname(String surname) { this.surname = surname; } }
11. Create the Index.xhtml
Let’s create a xhtml with the all input fields required for Customer, and our Index.xhtml is created as follows : This is the welcome page.
<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:p="http://primefaces.org/ui"> <h:head><title>Welcome to Java Beat for seeing PrimeFaces_Spring_Hibernate_Project</title></h:head> <h:body> <h:form> <table> <tr> <td><h:outputLabel for="id" value="Id : " /></td> <td><p:inputText id="id" value="#{customerMB.id}"> <f:converter converterId="javax.faces.Integer"/> <p:ajax event="blur" update="idMsg" /> </p:inputText> <p:message id="idMsg" for="id" display="icon"/> </td> </tr> <tr> <td><h:outputLabel for="name" value="Name : " /></td> <td><p:inputText id="name" value="#{customerMB.name}"> <f:validateLength minimum="5" /> <p:ajax event="blur" update="nameMsg" /> </p:inputText> <p:message id="nameMsg" for="name" display="icon"/> </td> </tr> <tr> <td><h:outputLabel for="surname" value="Surname : " /></td> <td><p:inputText id="surname" value="#{customerMB.surname}"> <f:validateLength minimum="5" /> <p:ajax event="blur" update="surnameMsg" /> </p:inputText> <p:message id="surnameMsg" for="surname" display="icon"/> </td> </tr> <tr> <td><p:commandButton id="addUser" value="Add" action="#{customerMB.addCustomer}" ajax="false"/></td> <td><p:commandButton id="reset" value="Reset" action="#{customerMB.reset}" ajax="false"/></td> </tr> </table> </h:form> </h:body> </html>
12. Create Success.xhtml
<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:p="http://primefaces.org/ui"> <h:head> <title>Welcome to Java Beat for seeing PrimeFaces_Spring_Hibernate_Project</title> </h:head> <h:body> <h:form> <h:outputText value="customers : "></h:outputText> <p:dataTable id="customers" var="customer" value="#{customerMB.customerList}" style="width: 10%"> <p:column> <f:facet name="header"> <h:outputText value="ID" /> </f:facet> <h:outputText value="#{customer.id}" /> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Name" /> </f:facet> <h:outputText value="#{customer.name}" /> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Surname" /> </f:facet> <h:outputText value="#{customer.surname}" /> </p:column> </p:dataTable> </h:form> </h:body> </html>
13. Run This Application
Run the Maven and primefacesSpring-1.0.war will be created in target folder. Now deploy primefacesSpring-1.0.war.After primefacesSpring-1.0 Project is deployed to Tomcat, index page can be opened via following URL.
http://IP:port/primefacesSpring-1.0/faces/index.xhtml
- [download id=”22″]
Summary
In this tutorial we saw the integration of Primefaces with Spring and hibernate by using minimal configuration. In next tutorials we will see the primefaces main libraries.