This tutorial guides you through creating a web application that integrates between PrimeFaces 5, Spring Data and MySQL database. It’s important for you to learn the basics of the technologies PrimeFaces and Spring Data before start reading this tutorial.
Also read:
1. Tools Required
It’s the required tools for being able to develop this tutorial:
- JDK 1.6+.
- Tomcat 7+.
- Spring 3.
- Primefaces 5.
- MySQL 5.
2. Java Beans (Business Domain)
Beans Address and Employees will be used as the entities for this tutorial.
Address.java
package net.javabeat.springdata.jpa.data; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity(name = "address") public class Address { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer addressId; private String addressCountry = ""; private String addressCity = ""; @OneToOne(cascade = CascadeType.ALL, mappedBy = "address") private Employee employee; public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public Integer getAddressId() { return addressId; } public void setAddressId(Integer addressId) { this.addressId = addressId; } public String getAddressCountry() { return addressCountry; } public void setAddressCountry(String addressCountry) { this.addressCountry = addressCountry; } public String getAddressCity() { return addressCity; } public void setAddressCity(String addressCity) { this.addressCity = addressCity; } }
Employee.java
package net.javabeat.springdata.jpa.data; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer employeeId; @Basic(optional = false) private String employeeName; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "Address") private Address address = new Address(); public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } }
3. Persistence Context
Here is the required persistence configuration, which contains the targeted database schema and its credential details and any additional configuration required like logging level and etc. Also this persistence configuration declare the above listed beans as the persistence entities.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="SpringData" transaction-type="RESOURCE_LOCAL"> <class>net.javabeat.springdata.jpa.data.Employee</class> <class>net.javabeat.springdata.jpa.data.Address</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.password" value="root" /> <property name="eclipselink.logging.level" value="OFF" /> </properties> </persistence-unit> </persistence>
4. Spring Data Repositories
Here is the spring data repository for each of the above entities. If you are familiar with the spring data repositories, these are just an abstract behaviour where the real implementation would be provided by the spring container at run time. It is the greatest advantage of using the spring data.
AddressRepository.java
package net.javabeat.springdata.repo; import net.javabeat.springdata.jpa.data.Address; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface AddressRepository extends CrudRepository<Address,Integer>{}
EmployeeRepository.java
package net.javabeat.springdata.repo; import net.javabeat.springdata.jpa.data.Employee; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends CrudRepository<Employee,Integer>{}
5. Spring Service
It’s just a spring bean that used for preventing the presentation layer talking directly with the repository. It’s just a type of orchestration that you would use. Spring bean will contain an instance of those defined repositories.
RegistrationService.java
package net.javabeat.springdata.beans; import net.javabeat.springdata.repo.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RegistrationService { @Autowired private EmployeeRepository employeeRepository; public EmployeeRepository getEmployeeRepository() { return employeeRepository; } public void setEmployeeRepository(EmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } }
6. Spring Context Configurations
It’s the minimal amount of lines that should be updated in the spring context, from which the Spring Container could initialize the beans and any other environment information needed for the spring container.
SpringContext.xml
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- For consider the using of annotations foe defining Spring Bean --> <context:annotation-config /> <!-- For defining Spring Bean --> <context:component-scan base-package="net.javabeat.springdata.beans" /> <!-- For bootstrapping the Spring Repository --> <jpa:repositories base-package="net.javabeat.springdata.repo" /> <!-- Necessary to get the entity manager injected into the factory bean --> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <!-- Define EclipseLink JPA Vendor Adapter --> <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"> <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" /> <property name="generateDdl" value="false" /> <property name="showSql" value="true" /> </bean> <!-- Entity Manager Factory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="SpringData"></property> <property name="jpaVendorAdapter" ref="jpaVendorAdapter" /> </bean> <!-- Transaction Manager --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!-- Enable Transactional Manner --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
7. Primefaces / JSF Faces Configuration
It’s the faces configuration XML file, defines the managed beans and spring expression resolver.
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2"> <application> <resource-bundle> <base-name>net.javabeat.jsf.application</base-name> <var>msg</var> </resource-bundle> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application> </faces-config>
8. Primefaces / JSF Managed Bean
It’s the user defined managed bean that contain the business logic of the registration business scenario used in this tutorial.
RegistrationManagedBean.java
package net.javabeat.primefaces.managedbeans; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import net.javabeat.springdata.beans.RegistrationService; import net.javabeat.springdata.jpa.data.Employee; import com.google.common.collect.Lists; @ManagedBean @SessionScoped public class RegistrationManagedBean { private Employee employee = new Employee(); private List<Employee> employees = new ArrayList<Employee>(); @ManagedProperty(value="#{registrationService}") private RegistrationService service; public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List<Employee> getEmployees() { this.employees = Lists.newArrayList(this.service.getEmployeeRepository().findAll()); return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } public RegistrationService getService() { return service; } public void setService(RegistrationService service) { this.service = service; } public String register(){ this.service.getEmployeeRepository().save(this.employee); this.employee = new Employee(); return ""; } }
9. Primefaces View
It’s the view that will be used for presenting the required primefaces UI components for Employee & Address registration business scenario.
index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:head> <script name="jquery/jquery.js" library="primefaces"></script> </h:head> <f:view> <h:form prependId="false"> <h2>JavaBeat Tutorials</h2> <h2>Primefaces + Spring Data + MySQL</h2> <h:panelGrid columns="2"> <h:outputText value="Enter Employee Name:"/> <p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText> <h:outputText value="Enter Employee Address Country:"/> <p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText> <h:outputText value="Enter Employee Address City:"/> <p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText> </h:panelGrid> <p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/> <p:separator/> <h:panelGrid columns="1" width="50%"> <p:dataTable value="#{registrationManagedBean.employees}" var="employee"> <p:column headerText="Employee's Name"> <h:outputText value="#{employee.employeeName}"/> </p:column> <p:column headerText="Employee's Country"> <h:outputText value="#{employee.address.addressCountry}"/> </p:column> <p:column headerText="Employee's City"> <h:outputText value="#{employee.address.addressCity}"/> </p:column> </p:dataTable> </h:panelGrid> </h:form> </f:view> </html>
10. Web Deployment Descriptor
It’s the required XML file that used by the Java EE container for understanding of the web application that will be getting deployed.
web.xml
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" metadata-complete="true" version="2.5"> <context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2 </description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>server</param-value> </context-param> <context-param> <param-name>javax.faces.application.CONFIG_FILES</param-name> <param-value>/WEB-INF/faces-config.xml</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-config/*.xml</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <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> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> </web-app>
11. PrimeFaces 5 + Spring Data + MySQL Demo
12. Database Records
13. Summary
Finally, we have implemented a web application that uses the PrimeFaces 5, Spring Data & MySQL. If you have any questions, please write it in the comments section.