SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
Spring Data JPA + JSF +
Maven + MySQL using
Eclipse IDE - Simple
Example to start with
I am in the process of learning Spring Data JPA and was trying a
lot to use it with a JSF Web Application created as a Maven
project through Eclipse. I was facing issues and ultimately getting
Null Pointer Exceptions at many places. After searching the
internet for a long time, still I could not find a simple example
which will explain the use of two frameworks together i.e. Spring
Data JPA and JSF.
But, one of my friends (Kunal Laud) helped me to overcome the
issues. I thought of sharing the application here as there might be
many learners like me who are facing similar issues. I hope this
document will be of some help.
1) Create a database table first. Below is the query which I used,
CREATE TABLE `Employee` (
`empid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
`address` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`salary` int(10) DEFAULT NULL,
PRIMARY KEY (`empid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
COLLATE=utf8_unicode_ci COMMENT='utf8_unicode_ci'
2) Then, I created a new maven project through Eclipse. Create a
simple project. Skip archetype selection.
3) Then on the next page, enter desired Group Id and Artifact Id.
Select war as packaging option.
4) Next, the most important thing is to update pom.xml with the
necessary dependencies. Below is the pom.xml file,
<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>com.empmgmnt.emp</groupId>
<artifactId>EmployeeMgmnt</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Employee Maven Webapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>repository.jboss.org-public</id>
<name>JBoss repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>
</repositories>
<properties>
<hibernate.version>4.0.1.Final</hibernate.version>
<mysql.connector.version>5.1.18</mysql.connector.version>
<slf4j.version>1.6.1</slf4j.version>
<spring.version>3.1.0.RELEASE</spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</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>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</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-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.160</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>4.1.0.Final</version>
</dependency>
<!-- MySQL JDBC connector -->
<!-- If you want to use MySQL, uncomment this dependency declation. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.7.1.RELEASE</version>
</dependency>
<!-- Logging dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- The JSR-303 Bean Validation API library. -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
</dependencies>
<build>
<finalName>EmpManagement</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Once you save the pom.xml file, Maven will automatically start
downloading the required dependencies. If not, you can
a) right click on project under Project Explorer
b) Click on Run As
c) Select maven install
5) Next, update the web.xml as follows
<?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>EmpManagement</display-name>
<!-- 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/hello.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-cl
ass>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- 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>
<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>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
6) Next, create Java classes as follows:-
Domain Entity:- Employee.java
package com.empmgmnt.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Employee")
public class Employee {
private String name;
private String address;
private Integer age;
private Integer salary;
@Id
private Integer empid;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getEmpid() {
return empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Repositories:- EmployeeRepository.java
package com.empmgmnt.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.empmgmnt.domain.Employee;
public interface EmployeeRepository extends JpaRepository<Employee,
Long>{
}
Service:- EmployeeService.java
package com.empmgmnt.services;
import java.util.List;
import com.empmgmnt.domain.Employee;
import com.empmgmnt.transferobjects.EmployeeDTO;
public interface EmployeeService {
public void create(EmployeeDTO emp);
public void delete(EmployeeDTO emp);
public Employee search(Integer id);
public List<Employee> findAll();
}
Service Implementation:- EmployeeServiceImpl.java
package com.empmgmnt.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.empmgmnt.domain.Employee;
import com.empmgmnt.repositories.EmployeeRepository;
import com.empmgmnt.transferobjects.EmployeeDTO;
@Component
@Service
public class EmployeeServiceImpl implements EmployeeService{
private static Integer new_emp_id=0;
private synchronized static Integer getNewEmpId(){
return new_emp_id++;
}
@Autowired
private EmployeeRepository employeeRepository;
private Employee getEmployee(EmployeeDTO employeeDTO){
Employee employee = new Employee();
employee.setEmpid(employeeDTO.getEmpid());
employee.setName(employeeDTO.getName());
employee.setAge(employeeDTO.getAge());
employee.setAddress(employeeDTO.getAddress());
employee.setSalary(employeeDTO.getSalary());
return employee;
}
@Override
public void create(EmployeeDTO emp) {
System.out.println("############ Saving service
##############");
Employee e = getEmployee(emp);
e.setEmpid(EmployeeServiceImpl.getNewEmpId());
employeeRepository.save(e);
System.out.println("########### After Saving service
##############");
}
@Override
public void delete(EmployeeDTO emp) {
employeeRepository.delete(getEmployee(emp));
}
@Override
public Employee search(Integer id) {
return employeeRepository.findOne(Long.valueOf(id));
}
@Override
public List<Employee> findAll() {
return employeeRepository.findAll();
}
}
Transfer Object:- EmployeeDTO.java
package com.empmgmnt.transferobjects;
import java.io.Serializable;
public class EmployeeDTO implements Serializable{
private String name;
private String address;
private Integer age;
private Integer salary;
private Integer empid;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getEmpid() {
return empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
User Interface (UI) Controller :- EmployeeBean.java
package com.empmgmnt.ui;
import java.io.Serializable;
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.empmgmnt.services.EmployeeService;
import com.empmgmnt.transferobjects.EmployeeDTO;
@Component
@Scope("session")
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String address;
private Integer age;
private Integer salary;
private Integer empid;
@Inject
@Autowired
EmployeeService employeeServiceImpl;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getEmpid() {
return empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void saveEmployee(){
System.out.println("############# Saving
################");
EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setAddress(this.getAddress());
employeeDTO.setName(this.getName());
employeeDTO.setAge(this.age);
employeeDTO.setSalary(this.salary);
System.out.println("############# impl ################
"+employeeServiceImpl);
employeeServiceImpl.create(employeeDTO);
System.out.println("#################### After Saving
##############");
}
}
7) Next, the .xhtml page is created as follows,
hello.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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<title>Employee</title>
</h:head>
<h:body>
<h3>Employee - hello.xhtml</h3>
<h:form>
<h:inputText value="#{employeeBean.name}"></h:inputText><br/>
<h:inputText value="#{employeeBean.address}"></h:inputText><br/>
<h:inputText value="#{employeeBean.age}"></h:inputText><br/>
<h:inputText value="#{employeeBean.salary}"></h:inputText><br/>
<h:commandButton id="cmd" value="submit" type="submit"
action="#{employeeBean.saveEmployee()}" />
</h:form>
</h:body>
</html>
8) Create persistence.xml file which contains the details about
persistent unit.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="empmgmnt"
transaction-type="RESOURCE_LOCAL">
<class>com.empmgmnt.domain.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/DATABASE"/>
<property name="javax.persistence.jdbc.user" value="USERNAME"/>
<property name="javax.persistence.jdbc.password"
value="PASSWORD"/>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.use_outer_join" value="true"/>
<property name="hibernate.cache.use_second_level_cache"
value="false"/>
<property name="hibernate.transaction.flush_before_completion"
value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
9) Create/update applicationContext.xml file to contain service
related details,
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.x
sd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/DATABASE</value>
</property>
<property name="username">
<value>USERNAME</value>
</property>
<property name="password">
<value>PASSWORD</value>
</property>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBea
n" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
>
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="empmgmnt" />
<property name="persistenceXmlLocation"
value="classpath:META-INF/persistence.xml" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
</bean>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.empmgmnt" />
<jpa:repositories base-package="com.empmgmnt.repositories"/>
<bean id="employeeService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBe
an">
<property name="transactionManager" ref="transactionManager" />
<property name="target" ref="employeeServiceImpl" />
<property name="proxyInterfaces">
<value>com.empmgmnt.services.EmployeeService</value>
</property>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_NOT_SUPPORTED, readOnly</prop>
</props>
</property>
</bean>
<bean id="employeeServiceImpl"
class="com.empmgmnt.services.EmployeeServiceImpl">
</bean>
</beans>
10) log4j.properties file
log4j.properties
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
11) faces-config.xml file which contains details about bean and
the navigation rules.
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
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_1.xsd">
<application>
<variable-resolver>
org.springframework.web.jsf.SpringBeanVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>employeeBean</managed-bean-name>
<managed-bean-class>com.empmgmnt.ui.EmployeeBean</managed-bean-cla
ss>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>employeeService</property-name>
<value>#{employeeService}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<navigation-case>
<from-outcome>index</from-outcome>
<to-view-id>/hello.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
</faces-config>
12) Web Application Execution
Hit the below URL,
http://localhost:8080/EmpManagement
Enter the necessary details on the form and click
submit. Below is the console output under Eclipse
IDE.
Creating instance of bean 'employeeBean'
Found injected element on class [com.empmgmnt.ui.EmployeeBean]: AutowiredFieldElement
for com.empmgmnt.services.EmployeeService
com.empmgmnt.ui.EmployeeBean.employeeServiceImpl
Processing injected method of bean 'employeeBean': AutowiredFieldElement for
com.empmgmnt.services.EmployeeService
com.empmgmnt.ui.EmployeeBean.employeeServiceImpl
Returning cached instance of singleton bean 'employeeServiceImpl'
Returning cached instance of singleton bean 'employeeService'
Returning cached instance of singleton bean
'org.springframework.transaction.config.internalTransactionAdvisor'
Autowiring by type from bean name 'employeeBean' to bean named 'employeeServiceImpl'
Returning cached instance of singleton bean
'org.springframework.transaction.config.internalTransactionAdvisor'
Finished creating instance of bean 'employeeBean'
############# Saving ################
############# impl ################
com.empmgmnt.services.EmployeeServiceImpl@6d8d0fdd
############ Saving service ##############
Adding transactional method 'save' with attribute:
PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
Returning cached instance of singleton bean 'transactionManager'
Creating new transaction with name
[org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]:
PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
Opened session at timestamp: 13938637982
Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c] for JPA transaction
begin
Obtaining JDBC connection
Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/study]
Obtained JDBC connection
initial autocommit status: true
disabling autocommit
Exposing JPA transaction as JDBC transaction
[org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@5d3f4
031]
Loading entity: [com.empmgmnt.domain.Employee#0]
select
employee0_.empid as empid0_0_,
employee0_.address as address0_0_,
employee0_.age as age0_0_,
employee0_.name as name0_0_,
employee0_.salary as salary0_0_
from
Employee employee0_
where
employee0_.empid=?
Hibernate:
select
employee0_.empid as empid0_0_,
employee0_.address as address0_0_,
employee0_.age as age0_0_,
employee0_.name as name0_0_,
employee0_.salary as salary0_0_
from
Employee employee0_
where
employee0_.empid=?
Initializing non-lazy collections
Done entity load
Generated identifier: 0, using strategy: org.hibernate.id.Assigned
Initiating transaction commit
Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c]
committing
Processing flush-time cascades
Dirty checking collections
Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
Listing entities:
com.empmgmnt.domain.Employee{empid=0, address=Mumbai, India, name=Nikhil, age=30,
salary=30000}
insert
into
Employee
(address, age, name, salary, empid)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
Employee
(address, age, name, salary, empid)
values
(?, ?, ?, ?, ?)
committed JDBC Connection
re-enabling autocommit
Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c] after transaction
Closing JPA EntityManager
HHH000420: Closing un-released batch
Releasing JDBC connection
Released JDBC connection
HHH000163: Logical connection releasing its physical connection
########### After Saving service ##############
#################### After Saving ##############
MySQL Database has the below entry:-

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Presentation Spring
Presentation SpringPresentation Spring
Presentation Spring
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Express node js
Express node jsExpress node js
Express node js
 
Ebook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoEbook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng cao
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
JavaScript Basic
JavaScript BasicJavaScript Basic
JavaScript Basic
 
Spring ioc
Spring iocSpring ioc
Spring ioc
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 
Advance Java Tutorial | J2EE, Java Servlets, JSP, JDBC | Java Certification T...
Advance Java Tutorial | J2EE, Java Servlets, JSP, JDBC | Java Certification T...Advance Java Tutorial | J2EE, Java Servlets, JSP, JDBC | Java Certification T...
Advance Java Tutorial | J2EE, Java Servlets, JSP, JDBC | Java Certification T...
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Web Development with NodeJS
Web Development with NodeJSWeb Development with NodeJS
Web Development with NodeJS
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Introduction to css
Introduction to cssIntroduction to css
Introduction to css
 
Bootstrap 5 basic
Bootstrap 5 basicBootstrap 5 basic
Bootstrap 5 basic
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 

Ähnlich wie Spring Data JPA + JSF + Maven + Mysql using Eclipse IDE

Vipul divyanshu mahout_documentation
Vipul divyanshu mahout_documentationVipul divyanshu mahout_documentation
Vipul divyanshu mahout_documentation
Vipul Divyanshu
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオン
haruki ueno
 

Ähnlich wie Spring Data JPA + JSF + Maven + Mysql using Eclipse IDE (20)

Spring RestFul Web Services - CRUD Operations Example
Spring RestFul Web Services - CRUD Operations ExampleSpring RestFul Web Services - CRUD Operations Example
Spring RestFul Web Services - CRUD Operations Example
 
Ajax, JSF, Facelets, Eclipse & Maven tutorials
Ajax, JSF, Facelets, Eclipse & Maven tutorialsAjax, JSF, Facelets, Eclipse & Maven tutorials
Ajax, JSF, Facelets, Eclipse & Maven tutorials
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
 
Java, Eclipse, Maven & JSF tutorial
Java, Eclipse, Maven & JSF tutorialJava, Eclipse, Maven & JSF tutorial
Java, Eclipse, Maven & JSF tutorial
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Apache Maven supports all Java (JokerConf 2018)
Apache Maven supports all Java (JokerConf 2018)Apache Maven supports all Java (JokerConf 2018)
Apache Maven supports all Java (JokerConf 2018)
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
 
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorialHibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorial
 
Spring Boot and JHipster
Spring Boot and JHipsterSpring Boot and JHipster
Spring Boot and JHipster
 
Maven: Managing Software Projects for Repeatable Results
Maven: Managing Software Projects for Repeatable ResultsMaven: Managing Software Projects for Repeatable Results
Maven: Managing Software Projects for Repeatable Results
 
Integrating Maven with Eclipse
Integrating Maven with EclipseIntegrating Maven with Eclipse
Integrating Maven with Eclipse
 
Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
Using MongoDB and a Relational Database at MongoDB Day
Using MongoDB and a Relational Database at MongoDB DayUsing MongoDB and a Relational Database at MongoDB Day
Using MongoDB and a Relational Database at MongoDB Day
 
Gradle: From Extreme to Mainstream
Gradle: From Extreme to MainstreamGradle: From Extreme to Mainstream
Gradle: From Extreme to Mainstream
 
Vipul divyanshu mahout_documentation
Vipul divyanshu mahout_documentationVipul divyanshu mahout_documentation
Vipul divyanshu mahout_documentation
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオン
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Spring Data JPA + JSF + Maven + Mysql using Eclipse IDE

  • 1. Spring Data JPA + JSF + Maven + MySQL using Eclipse IDE - Simple Example to start with
  • 2. I am in the process of learning Spring Data JPA and was trying a lot to use it with a JSF Web Application created as a Maven project through Eclipse. I was facing issues and ultimately getting Null Pointer Exceptions at many places. After searching the internet for a long time, still I could not find a simple example which will explain the use of two frameworks together i.e. Spring Data JPA and JSF. But, one of my friends (Kunal Laud) helped me to overcome the issues. I thought of sharing the application here as there might be many learners like me who are facing similar issues. I hope this document will be of some help. 1) Create a database table first. Below is the query which I used, CREATE TABLE `Employee` ( `empid` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `address` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `age` int(3) DEFAULT NULL, `salary` int(10) DEFAULT NULL, PRIMARY KEY (`empid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='utf8_unicode_ci' 2) Then, I created a new maven project through Eclipse. Create a simple project. Skip archetype selection. 3) Then on the next page, enter desired Group Id and Artifact Id. Select war as packaging option. 4) Next, the most important thing is to update pom.xml with the necessary dependencies. Below is the pom.xml file, <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  • 3. 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>com.empmgmnt.emp</groupId> <artifactId>EmployeeMgmnt</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Employee Maven Webapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>repository.jboss.org-public</id> <name>JBoss repository</name> <url>https://repository.jboss.org/nexus/content/groups/public</url> </repository> </repositories> <properties> <hibernate.version>4.0.1.Final</hibernate.version> <mysql.connector.version>5.1.18</mysql.connector.version> <slf4j.version>1.6.1</slf4j.version> <spring.version>3.1.0.RELEASE</spring.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</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> <scope>provided</scope> </dependency>
  • 4. <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.sun.el</groupId> <artifactId>el-ri</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</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>
  • 5. <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- Spring Data JPA --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons-core</artifactId> <version>1.2.1.RELEASE</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.160</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator-annotation-processor</artifactId> <version>4.1.0.Final</version> </dependency>
  • 6. <!-- MySQL JDBC connector --> <!-- If you want to use MySQL, uncomment this dependency declation. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <dependency> <groupId>com.jolbox</groupId> <artifactId>bonecp</artifactId> <version>0.7.1.RELEASE</version> </dependency> <!-- Logging dependencies --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <!-- The JSR-303 Bean Validation API library. --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> </dependencies> <build> <finalName>EmpManagement</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins>
  • 7. </build> </project> Once you save the pom.xml file, Maven will automatically start downloading the required dependencies. If not, you can a) right click on project under Project Explorer b) Click on Run As c) Select maven install 5) Next, update the web.xml as follows <?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>EmpManagement</display-name> <!-- 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/hello.xhtml</welcome-file> </welcome-file-list> <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-cl ass> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup>
  • 8. </servlet> <servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/spring/*</url-pattern> </servlet-mapping> <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <!-- 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> <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>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value>
  • 9. </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> </web-app> 6) Next, create Java classes as follows:- Domain Entity:- Employee.java package com.empmgmnt.domain; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Employee") public class Employee { private String name; private String address; private Integer age; private Integer salary; @Id private Integer empid; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSalary() { return salary; }
  • 10. public void setSalary(Integer salary) { this.salary = salary; } public Integer getEmpid() { return empid; } public void setEmpid(Integer empid) { this.empid = empid; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Repositories:- EmployeeRepository.java package com.empmgmnt.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.empmgmnt.domain.Employee; public interface EmployeeRepository extends JpaRepository<Employee, Long>{ } Service:- EmployeeService.java package com.empmgmnt.services; import java.util.List; import com.empmgmnt.domain.Employee; import com.empmgmnt.transferobjects.EmployeeDTO; public interface EmployeeService { public void create(EmployeeDTO emp); public void delete(EmployeeDTO emp);
  • 11. public Employee search(Integer id); public List<Employee> findAll(); } Service Implementation:- EmployeeServiceImpl.java package com.empmgmnt.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.empmgmnt.domain.Employee; import com.empmgmnt.repositories.EmployeeRepository; import com.empmgmnt.transferobjects.EmployeeDTO; @Component @Service public class EmployeeServiceImpl implements EmployeeService{ private static Integer new_emp_id=0; private synchronized static Integer getNewEmpId(){ return new_emp_id++; } @Autowired private EmployeeRepository employeeRepository; private Employee getEmployee(EmployeeDTO employeeDTO){ Employee employee = new Employee(); employee.setEmpid(employeeDTO.getEmpid()); employee.setName(employeeDTO.getName()); employee.setAge(employeeDTO.getAge()); employee.setAddress(employeeDTO.getAddress()); employee.setSalary(employeeDTO.getSalary()); return employee; } @Override public void create(EmployeeDTO emp) { System.out.println("############ Saving service ##############"); Employee e = getEmployee(emp);
  • 12. e.setEmpid(EmployeeServiceImpl.getNewEmpId()); employeeRepository.save(e); System.out.println("########### After Saving service ##############"); } @Override public void delete(EmployeeDTO emp) { employeeRepository.delete(getEmployee(emp)); } @Override public Employee search(Integer id) { return employeeRepository.findOne(Long.valueOf(id)); } @Override public List<Employee> findAll() { return employeeRepository.findAll(); } } Transfer Object:- EmployeeDTO.java package com.empmgmnt.transferobjects; import java.io.Serializable; public class EmployeeDTO implements Serializable{ private String name; private String address; private Integer age; private Integer salary; private Integer empid; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; }
  • 13. public void setAge(Integer age) { this.age = age; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public Integer getEmpid() { return empid; } public void setEmpid(Integer empid) { this.empid = empid; } public String getName() { return name; } public void setName(String name) { this.name = name; } } User Interface (UI) Controller :- EmployeeBean.java package com.empmgmnt.ui; import java.io.Serializable; import javax.inject.Inject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.empmgmnt.services.EmployeeService; import com.empmgmnt.transferobjects.EmployeeDTO; @Component @Scope("session") public class EmployeeBean implements Serializable { private static final long serialVersionUID = 1L;
  • 14. private String name; private String address; private Integer age; private Integer salary; private Integer empid; @Inject @Autowired EmployeeService employeeServiceImpl; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public Integer getEmpid() { return empid; } public void setEmpid(Integer empid) { this.empid = empid; } public String getName() { return name; } public void setName(String name) { this.name = name; }
  • 15. public void saveEmployee(){ System.out.println("############# Saving ################"); EmployeeDTO employeeDTO = new EmployeeDTO(); employeeDTO.setAddress(this.getAddress()); employeeDTO.setName(this.getName()); employeeDTO.setAge(this.age); employeeDTO.setSalary(this.salary); System.out.println("############# impl ################ "+employeeServiceImpl); employeeServiceImpl.create(employeeDTO); System.out.println("#################### After Saving ##############"); } } 7) Next, the .xhtml page is created as follows, hello.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:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:head> <title>Employee</title> </h:head> <h:body> <h3>Employee - hello.xhtml</h3> <h:form> <h:inputText value="#{employeeBean.name}"></h:inputText><br/> <h:inputText value="#{employeeBean.address}"></h:inputText><br/> <h:inputText value="#{employeeBean.age}"></h:inputText><br/> <h:inputText value="#{employeeBean.salary}"></h:inputText><br/> <h:commandButton id="cmd" value="submit" type="submit" action="#{employeeBean.saveEmployee()}" /> </h:form> </h:body> </html>
  • 16. 8) Create persistence.xml file which contains the details about persistent unit. persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="empmgmnt" transaction-type="RESOURCE_LOCAL"> <class>com.empmgmnt.domain.Employee</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/DATABASE"/> <property name="javax.persistence.jdbc.user" value="USERNAME"/> <property name="javax.persistence.jdbc.password" value="PASSWORD"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="hibernate.archive.autodetection" value="class"/> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.use_outer_join" value="true"/> <property name="hibernate.cache.use_second_level_cache" value="false"/> <property name="hibernate.transaction.flush_before_completion" value="true" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
  • 17. 9) Create/update applicationContext.xml file to contain service related details, applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:context="http://www.springframework.org/schema/context" xmlns:repository="http://www.springframework.org/schema/data/repository" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.x sd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/DATABASE</value> </property> <property name="username"> <value>USERNAME</value> </property> <property name="password"> <value>PASSWORD</value> </property> </bean> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBea n" />
  • 18. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="empmgmnt" /> <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="database" value="MYSQL" /> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="dataSource" ref="dataSource" /> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <context:component-scan base-package="com.empmgmnt" /> <jpa:repositories base-package="com.empmgmnt.repositories"/> <bean id="employeeService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBe an"> <property name="transactionManager" ref="transactionManager" /> <property name="target" ref="employeeServiceImpl" /> <property name="proxyInterfaces"> <value>com.empmgmnt.services.EmployeeService</value> </property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_NOT_SUPPORTED, readOnly</prop> </props> </property> </bean> <bean id="employeeServiceImpl" class="com.empmgmnt.services.EmployeeServiceImpl"> </bean> </beans>
  • 19. 10) log4j.properties file log4j.properties log4j.rootLogger=debug, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 11) faces-config.xml file which contains details about bean and the navigation rules. faces-config.xml <?xml version="1.0" encoding="UTF-8"?> <faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" 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_1.xsd"> <application> <variable-resolver> org.springframework.web.jsf.SpringBeanVariableResolver </variable-resolver> </application> <managed-bean> <managed-bean-name>employeeBean</managed-bean-name> <managed-bean-class>com.empmgmnt.ui.EmployeeBean</managed-bean-cla ss> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>employeeService</property-name> <value>#{employeeService}</value> </managed-property> </managed-bean> <navigation-rule> <navigation-case> <from-outcome>index</from-outcome> <to-view-id>/hello.xhtml</to-view-id> <redirect /> </navigation-case> </navigation-rule> </faces-config>
  • 20. 12) Web Application Execution Hit the below URL, http://localhost:8080/EmpManagement Enter the necessary details on the form and click submit. Below is the console output under Eclipse IDE. Creating instance of bean 'employeeBean' Found injected element on class [com.empmgmnt.ui.EmployeeBean]: AutowiredFieldElement for com.empmgmnt.services.EmployeeService com.empmgmnt.ui.EmployeeBean.employeeServiceImpl Processing injected method of bean 'employeeBean': AutowiredFieldElement for com.empmgmnt.services.EmployeeService com.empmgmnt.ui.EmployeeBean.employeeServiceImpl Returning cached instance of singleton bean 'employeeServiceImpl' Returning cached instance of singleton bean 'employeeService' Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor' Autowiring by type from bean name 'employeeBean' to bean named 'employeeServiceImpl' Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor' Finished creating instance of bean 'employeeBean' ############# Saving ################ ############# impl ################ com.empmgmnt.services.EmployeeServiceImpl@6d8d0fdd ############ Saving service ############## Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' Returning cached instance of singleton bean 'transactionManager' Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' Opened session at timestamp: 13938637982 Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c] for JPA transaction begin Obtaining JDBC connection Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/study] Obtained JDBC connection initial autocommit status: true disabling autocommit Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@5d3f4 031] Loading entity: [com.empmgmnt.domain.Employee#0]
  • 21. select employee0_.empid as empid0_0_, employee0_.address as address0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_, employee0_.salary as salary0_0_ from Employee employee0_ where employee0_.empid=? Hibernate: select employee0_.empid as empid0_0_, employee0_.address as address0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_, employee0_.salary as salary0_0_ from Employee employee0_ where employee0_.empid=? Initializing non-lazy collections Done entity load Generated identifier: 0, using strategy: org.hibernate.id.Assigned Initiating transaction commit Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c] committing Processing flush-time cascades Dirty checking collections Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections Listing entities: com.empmgmnt.domain.Employee{empid=0, address=Mumbai, India, name=Nikhil, age=30, salary=30000} insert into Employee (address, age, name, salary, empid) values (?, ?, ?, ?, ?) Hibernate: insert into Employee (address, age, name, salary, empid) values (?, ?, ?, ?, ?) committed JDBC Connection re-enabling autocommit Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@3fe3b1c] after transaction Closing JPA EntityManager HHH000420: Closing un-released batch Releasing JDBC connection Released JDBC connection HHH000163: Logical connection releasing its physical connection ########### After Saving service ############## #################### After Saving ##############
  • 22. MySQL Database has the below entry:-