Spring4,Primefaces5,SpringDataJPA
and Hibernate4 CRUD Application Using Netbeans8.02 IDE and MySQL Database
Server
This
simple application is a Create, Retrieve, Update and Delete (CRUD) application
operating on an ‘employee’ table in ‘springdatacruddb’ database in MySQL
Database Server. It is a Primefaces, Spring, SpringDataJPA and
Hibernate-annotation based application.
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.** and Primefaces 5.0(Bundled with Netbeans)
6.Spring4.3.2
7.SpringDataJPA1.11.0
Eclipse can also be used for developing this application.
For Integrating Maven,
pom.xml is provided at the end of this tutorial.
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 ) .
Create
springdatacruddb database in MySQL
Database Server.
After
Installing Netbeans click the services tab on the left.Expand Database node.
Expand Drivers node. Right click MySQL(Connector/Jdriver) then connect. Put
springdatacruddb as the database. As shown below. Put password if you have
given password at the time of installation of MySQL database server. For XAMPP no password is required. Then test connection.
If successful click finish button.
Create
user table by running below SQL in ‘springdatacruddb’ database
CREATE
TABLE IF NOT EXISTS `employee` (
`EmpId` int(15) NOT NULL,
`FirstName` varchar(25) NOT NULL,
`LastName` varchar(25) NOT NULL,
`Salary` int(20) NOT NULL,
`Sex` varchar(15) NOT NULL,
`DOB` date NOT NULL,
`Remark` varchar(50) NOT NULL
)
ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER
TABLE `employee` ADD PRIMARY KEY
(`EmpId`);
INSERT
INTO `employee` (`EmpId`, `FirstName`, `LastName`, `Salary`, `Sex`, `DOB`,
`Remark`) VALUES
(1,
'Andrei', 'Agassi', 2000000, 'Male', '1980-06-18', 'Very Good Tennis Player'),
(2,
'Martina', 'Navratilova', 60000000, 'Female', '1978-12-15', 'Very Good Tennis
Player'),
(3,
'Venus', 'Williams', 7000000, 'Female', '1975-12-21', 'Very Goog Tennis
Player'),
(4,
'Roger', 'Fedrer', 600000, 'Male', '1987-12-20', 'Very Good Tennis Player'),
(5,
'Lindsay', 'Devonport', 600000, 'Female', '1974-12-14', 'Very good Tennis Player '),
(6,
'Serena', 'Williams', 600000, 'Female', '1988-12-16', 'Very Good Tennis
Player'),
(7,
'Barak', 'Obama', 5463216, 'Male', '1961-12-18', 'Ex-President USA'),
(8,
'Mary', 'Pierce', 8654321, 'Female', '1983-06-14', 'Very good beautiful Tennis
Player'),
(9,
'Rafel', 'Nadal', 754321, 'Male', '1991-04-12', 'Very Goog Tennis Player'),
(10,
'Sir Donald', 'Bradman', 650000, 'Male', '1942-05-06', 'Very Good Cricket
Bowler'),
(11,
'Usin', 'Bolt', 690700, 'Male', '1998-12-16', 'Olympics Gold Medalist in Athletics'),
(12,
'Micheal', 'Phelps', 765000, 'Male', '1992-12-22', 'Olympics Gold Medalist in Swimming.USA Citizen.'),
(13,
'Andy', 'Moore', 750000, 'Male', '1991-05-09', 'Very Goog Tennis Player'),
(14,
'Tom', 'Cruise', 7000000, 'Male', '1975-01-15', 'Hollywood Actor'),
(15,
'Maria', 'Sharpova', 8000000, 'Female', '1980-04-06', 'Very Good Beautiful
Tennis Player'),
(16,
'Martina', 'Hingis', 850000, 'Female', '1982-02-18', 'Very Goog Tennis
Player'),
(17,
'Vin', 'Diesel', 840000, 'Male', '1985-01-17', 'Very Good Actor'),
(18,
'Angelina', 'Jolie', 7500000, 'Female', '1987-11-14', 'Very Good Actress'),
(19,
'Brad', 'Pitt', 765000, 'Male', '1979-01-24', 'Very Good Actor'),
(20,
'Steffi', 'Graff', 780000, 'Female', '1984-12-10', 'Very Good Beautiful Tennis
Player');
JARS required to be added
to Libraries Folder
Right click on the Libraries folderà addJAR/Folder then add 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
5. Jandex-2.0.3
6. spring-aop-4.3.2
7. spring-beans-4.3.2
8. spring-context-4.3.2
9. spring-core-4.3.2
10. spring-tx-4.3.2
11. spring-web-4.3.2
12. spring-expression-4.3.2
13. spring-jdbc-4.3.2
14. spring-orm-4.3.2
15. Spring-data-commons-1.12.5
16. Spring-data-jpa-1.10.5
Creating Project MavenPrimefacesSpringDataJPACRUD
File-àNew
ProjectàCategories-àChoose JavaWeb--àChoose WebApplicationàClick Next-àGive Project Name MavenPrimefacesSpringDataJPACRUDà
Click NextàClick
NextàChoose Framework First Hibernate then Java Server Faces--àClick
Component Tab-àChoose Primefacesà Click Finish
In the above figure Database Connection
should be with ‘springdatacruddb’ database.
In the above figure Database Connection should
be with ‘springdatacruddb’ database
Download mysql-
connector-java-bin.jar add to libraries folder by right click addJAR/Folderàadd the mysql-java-bin.jar.
Create a folder named View under Web
pages Folder.Delete WelcomePrimefaces.xhtml .View Folder would contain crud.xhtml
File
Project Structure
Creating Packages and Classes
Right
click Source Package folder and create five packages
1.org.ray.jsfbean.controller-->This
would contain JSF Managed Bean Class EmployeeBean.java
2.
org.ray.springdataJpa.dao.repositories-àThis would contain
DAO(Data Access Object) Repositories EmployeeRepository.java
3.org.ray.springdatajpa.exceptionàThis would contain one
file EmployeeNotFoundException.java
4.
org.ray.hibernate.pojos.modelàThis would contain entity
(POJO) class files
Employee.java.
POJO Stands for Plain Old Java Objects
5.
org.ray.spring.serviceàThis would contain Spring
Service class files
EmployeeService.java and EmployeeServiceImpl.Java.
Following
Files would be created using Netbeans
1.
hibernate.cfg.xml File-àAutomatically generated. (It
will be used to create Employee.java and
then would be deleted.)
2.
Reverse Engineering File-àhibernate.reveng.xml. (It will be used to
create Employee.java and then would be deleted.)
3.Entity(POJO)
File-àEmployee.java (POJO stands for Plain Old Java Objects)
4.JSF Managed Bean
File-àEmployeeBean.ja va
5.Employee
Repository FileàEmployeeRepository.java
6.Exception
handling FileàEmployeeNotFoundException.java
7.SpringService FileàEmployeeService .java and EmployeeServiceImpl.java
8. crud.xhtmlàThis
is single page which is displayed on lunch of application.
9.faces-config.xmlàIt
is to be added after creating under WEB-INF folder if not there.
10. web.xml (Automatically
generated)
11. spring-database.xmlàThis
contains spring file database access credentials.
Add mysql-
connector-java-bin.jar to libraries if not done.
COPY
AND PASTE CODE OF THE FILE GIVEN BELOW
WHOSE CODE IS NOT GENERATED
1.Hibernate.cfg.xml File(It would be deleted after used for
creating Employee.java entity class)
As XAMPP is used so there is no
password in the file only username
is given that is root in
Hibernate.cfg.xml File.
Code:-
<?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://localhost:3306/ springdatacruddb?zeroDateTimeBehavior=convertToNull</property>
<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="org.ray.hibernate.pojos.model.Employee"/>
</session-factory>
</hibernate-configuration>
2. Creating Reverse Engineering
File-àhibernate.reveng.xml(It would be deleted after used
for creating Employee.java entity class).
Right Click default package in the Source
Package-ànewàchoose Hibernate Reverse Engineering Wizardàclick
nextàchoose employee 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=" springdatacruddb "/>
<table-filter match-name="employee"/>
</hibernate-reverse-engineering>
3. Creating Hibernate Entity
(pojo) File:-Employee.java
Important:To create this
file MySQL database springdatacruddb most be connected through Netbeans.
Right
click com.model package--ànew-àHibernate Mappling Files
and pojos from databaseàDonot select mapping file,select
EJB3.0 Pattern and Domain Code(java) and also select JDK5 Language Features(Though not shown below)àCliek Finish
Employee.java CODE:
package
org.ray.hibernate.pojos.model;
//
Generated Nov 30, 2016 11:34:46 AM by Hibernate Tools 4.3.1
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;
/**
*
* @author Raichand
*/
@Entity
@Table(name="employee"
,catalog="springdatacruddb"
)
public
class Employee implements
java.io.Serializable {
private int empId;
private String firstName;
private String lastName;
private int salary;
private String sex;
private Date dob;
private String remark;
@Id
@Column(name="EmpId",
unique=true, nullable=false)
public int getEmpId() {
return this.empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
@Column(name="FirstName",
nullable=false, length=25)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
@Column(name="LastName",
nullable=false, length=25)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name="Salary",
nullable=false)
public int getSalary() {
return this.salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Column(name="Sex",
nullable=false, length=15)
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Temporal(TemporalType.DATE)
@Column(name="DOB",
nullable=false, length=10)
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Column(name="Remark", nullable=false,
length=50)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public
void reset() {
this.setEmpId(0);
this.setFirstName("");
this.setLastName("");
this.setSex("");
this.setSalary(0);
this.setDob(null);
this.setRemark("");
}
//This method writes the values of employee
object with System.out.println(employee.toString()) code
@Override
public String toString() {
return "employee"
+ "\n\t Id: " + this.empId
+ "\n\t FirstName: " +
this.firstName
+ "\n\t LastNmae: " +
this.lastName
+ "\n\t Sex: " + this.sex
+ "\n\t Salary: " +
this.salary
+ "\n\t Date of Birth: " +
this.dob
+ "\n\t Remark: " + this.remark;
}
}
4. Creating JSF Managed Bean File
EmployeeBean.java File
Right
click org.ray.jsfbean.controller
package--ànew-àJSF Managed BeanàGive class name EmployeeBean-à click finish.
Download attached source code compressed
winrar file then copy and paste it.
5. Creating Spring Service File
EmployeService.java and
EmployeeServiceImpl File
Right
click org.ray.spring.service package--ànew-àJava ClassàGive class name EmployeService click
finish.
Similarly
EmployeeServiceImpl File can be created.
Download attached source code compressed winrar
file then copy and paste it.
6.Employee Repository Files
Download attached source code compressed
winrar file then copy and paste it.
7.EmployeeNotFoundException
File Download attached source code winrar file then
copy and paste it.
Download attached source code compressed
winrar file then copy and paste it.
8. crud.xhtml code
Download attached source code compressed
winrar file then copy and paste it.
9. faces-config.xml
It
is created using notepad and 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://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<!--
JSF and Spring are integrated -->
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
10. web.xml (Automatically
generated and modified later)
<?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://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>Employee Management</display-name>
<!--
Declare Spring configuration file location -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<!-- Spring -->
<!--
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 -->
<!-- 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>
<!--
Mapping with servlet and url for the http requests. -->
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!--
Welcome Page -->
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
11. spring-database.xml (Add
if not aomatically generated and modified later)
Download attached source code compressed winrar
file then copy and paste it.
crud.xhtml page
Adding
New Employee
Edit
Employee
Delete Employee
Filtering
First Name Starting with ‘S’
pom.xml
<?xml
version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.raywebsites</groupId>
<artifactId>MavenPrimefacesSpringDataJPACRUD</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>MavenPrimefacesSpringDataJPACRUD</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!--Javax inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!--Java Annotation Indexer -->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.3.Final</version>
</dependency>
<!-- aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!--Spring Framework-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!--spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.13.1.RELEASE</version>
</dependency>
<!-- Spring Data JPA dependencies
-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.0.RELEASE</version>
</dependency>
<!-- aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<!-- querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
</dependency>
<!-- aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<!--Web Dependencies-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
</dependency>
<!--Java Server Faces-->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.7</version>
</dependency>
<!--Primefaces-->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0</version>
</dependency>
<!--Hibernate-->
<!-- hibernate-entitymanager
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!--hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!-- Database dependencies -->
<!-- MySql Connector -->
<dependency>
<groupId> mysql
</groupId>
<artifactId>
mysql-connector-java </artifactId>
<version> 5.1.35
</version>
</dependency>
<!-- commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<url>http://repository.primefaces.org/</url>
<id>PrimeFaces-maven-lib</id>
<layout>default</layout>
<name>Repository for library
PrimeFaces-maven-lib</name>
</repository>
</repositories>
</project>
Project Files can be downloaded from below URL
https://www.dropbox.com/s/1gvcpiuysfsuskm/MavenPrimefacesSpringDataJPACRUD.rar?dl=0