0% found this document useful (0 votes)
43 views

Spring Notes & Programs

Uploaded by

2100090063csit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Spring Notes & Programs

Uploaded by

2100090063csit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 125

Spring

 Spring is a light weight and open source framework created by Rod


Johnson in 2003.
Spring is a lightweight application development framework used for Java
Enterprise Edition (JEE).

 Spring is light weight framework because of its POJO model


Java Spring is easy to learn as the entire Spring framework is designed to work
with POJOs rather than depending on special interfaces, abstract classes, etc.

 Works on POJOs (Plain Old Java Object) which makes your application
lightweight.
 Provides predefined templates for JDBC, Hibernate, etc., thus reducing your
effort of writing too much code.
 Because of dependency injection feature, your code becomes loosely
coupled.
 Using Spring Framework, the development of Java Enterprise
Edition (JEE) applications became faster.
 It also provides strong abstraction to Java Enterprise Edition (JEE)
specifications.

Advantages.

 Simplicity
 Testability
 Loose Coupling

Simplicity
Spring framework is simple because as it is non-
invasive, POJO and POJI model
Testability
For writing the spring application, server [Container] is
not mandatory, but for struts applications we need a
server, and for EJB too.

Loose Coupling
In spring objects are loosely coupled, this is
the core concept of spring framework.

Features Of Spring Framework

 Lightweight: Spring Framework is lightweight with respect to size and


transparency.

 Inversion Of Control (IoC): In Spring Framework, loose coupling


is achieved using Inversion of Control. The objects give their own
dependencies instead of creating or looking for dependent objects.

 Aspect Oriented Programming (AOP): By separating application business


logic from system services, Spring Framework supports Aspect Oriented
Programming and enables cohesive development.

 Container: Spring Framework creates and manages the life cycle and
configuration of application objects.

 MVC Framework: Spring Framework is a MVC web application


framework. This framework is configurable via interfaces and
accommodates multiple view technologies.

 Transaction Management: For transaction management, Spring framework


provides a generic abstraction layer. It is not tied to J2EE environments and
it can be used in container-less environments.
 JDBC Exception Handling: The JDBC abstraction layer of the Spring
Framework offers an exception hierarchy, which simplifies the error
handling strategy.
Spring Framework Architecture

Spring Framework architecture is an arranged layered architecture that consists of


different modules. All the modules have their own functionalities that are utilized
to build an application. There are around 20 modules that are generalized
into Core Container, Data Access/ Integration, Web, AOP (Aspect Oriented
Programming), Instrumentation, and Test. Here, the developer is free to choose
the required module. Its modular architecture enables integration with other
frameworks without much hassle.
Core Container

This container has the following four modules :

1. Spring Core: This module is the core of the Spring Framework. It provides
an implementation for features like IoC (Inversion of Control) and
Dependency Injection with a singleton design pattern.
2. Spring Bean: This module provides an implementation for the factory
design pattern through BeanFactory.
3. Spring Context: This module is built on the solid base provided by the Core
and the Beans modules and is a medium to access any object defined and
configured.
4. Spring Expression Languages (SpEL): This module is an extension to
expression language supported by Java server pages. It provides a powerful
expression language for querying and manipulating an object graph, at
runtime.

Spring Data Access/ Integration

1. JDBC: This module provides JDBC abstraction layer which eliminates the
need of repetitive and unnecessary exception handling overhead.
2. ORM: ORM stands for Object Relational Mapping. This module provides
consistency/ portability to our code regardless of data access technologies
based on object oriented mapping concept.
3. OXM: OXM stands for Object XML Mappers. It is used to convert the
objects into XML format and vice versa. The Spring OXM provides an
uniform API to access any of these OXM frameworks.
4. JMS: JMS stands for Java Messaging Service. This module contains
features for producing and consuming messages among various clients.
5. Transaction: This module supports programmatic and declarative
transaction management for classes that implement special interfaces and for
all your POJOs. All the enterprise level transaction implementation concepts
can be implemented in Spring by using this module.
Spring Web

1. Web: This module using servlet listeners and a web-oriented application


context, provides basic web-oriented integration features like multi-part file
upload functionality and the initialization of the IoC container.
2. Web-Servlet: This module contains Model-View-Controller (MVC) based
implementation for web applications. It provides all other features of MVC,
including UI tags and data validations.
3. Web-Socket: This module provides support for WebSocket based and two-
way communication between the client and the server in web applications.
4. Web-Portlet: This module is also known as the Spring-MVC-
Portlet module. It provides the support for Spring-based Portlets and mirrors
the functionality of a Web-Servlet module.

Aspect-Oriented Programming (AOP)

AOP language is a powerful tool that allows developers to add enterprise


functionality to the application such as transaction, security etc. It allows us to
write less code and separate the code logic. AOP uses cross-cutting concerns.

Instrumentation

This module provides class instrumentation support and classloader


implementations that are used in certain application servers.

Test

This module supports the testing of Spring components with JUnit or TestNG. It
provides consistent loading of Spring ApplicationContexts and caching of those
contexts. It also provides mock objects that we can use to test our code in isolation.
Spring Modules
Actually in spring 1.x, the framework has divided into 7 well defined
modules. But in2.x framework is divided into 6 modules only..

 Spring Core Module


 Spring Context [ J2EE ]
 Spring DAO Module [ Spring JDBC ]
 Spring ORM module
 Spring AOP [ Aspect Oriented Programming ]
 Spring WEB-MVC Module

Actually in spring 1.x, web, mvc are given as separate modules…


Spring Core Module is the base for all modules.

Spring DAO Spring Spring


A J2EE WEB
MVC
O

P
ORM

Spring Core Container


let us see one by one module in depth…..
Spring Core Module, Spring IOC :
Core Module is the heart of Spring, tight coupling
and loose coupling is the heart concept of Core Module.

Tight Coupling Between Java Objects


class Car
{
void move()
{
System.out.println(“moving”);
}
}

class Traveler
{
Car c=new Car();
void startJourney()
{
c.move();
}
}

class Main
{
public static void main(String args[])
{
Traveler t=new Traveler();
t.startJourney();
}
}
 In the above example, Traveler object is depends on car object. So
traveler class creating an object of Car class inside it.
 If the other class object is created in the dependent class [ like Car class
object in Traveler class ], there exist tight coupling, i mean if method in
car object is changed then we need to do the changes in the Traveler
class too so its the tight coupling between Traveler and Car class
objects.

Loose Coupling Between Java Objects


Loose coupling in Java means that the classes are independent of
each other.

In order to over come tight coupling between objects,


spring framework uses dependency injection mechanism
with the help of POJO/POJI model and
through dependency injection its possible to achieve
loose coupling.

In the above example Traveler , Car are tightly coupled.


If we want to achieve loose coupling between the objects
Traveler and Car.
Code:-
interface Vehicle
{
void move();
}

class Car implements Vehicle


{
public void move()
{
System.out.println(“car moving”);
}
}

class Bike implements Vehicle


{
public void move()
{
System.out.println("Bike moving");
}
}
class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

void startJourney()
{
v.move();
}
}
In above example, spring container will inject either Car object
or Bike object into theTraveler by calling setter method, So if Car object
is replaced with Bike then no changes are required in Traveler class, this
means there is loose coupling between Traveler and Vehicle object.

Spring Application Steps


-------------------------------------------------------------------------------

1. Create the Bean.java class(POJO)


2. Create a XML/ configuration file(applicationContext.xml)
3. Create the main class(App.java)
4. Load the required jar files
5. Run the application

Step I: Creating the Bean class:

 For this go to File > New > Java Project.


 Now to create a package, right click on Project > New > package.
 Name the package and again right click on New > Class.

Step II: Create a XML file

 Right click on src > New > Other > XML File

 The <bean> tag is used to define the bean for the given class.

 The <property> tag is a subelement of bean, and specifies the property of


the class. The value specified in the property element will be set in the class
object by the IoC container.

Step III: Create the main class

 Right click on package > New > Class

Step IV: Load the jar files.


Steps to create MAVEN Spring project in Eclipse

----------------------------------------------------------------------------------

1)goto file->new->project->search MAVEN

select maven project

use default workspace location select

next

select org.apache.maven.archetypes maven-archetype-quickstart version


1.1

next

OR

select Artifact-id :

maven-archetype-quickstart

version : 1.1

next

Group id : com.klu

Artifact id : SpringDemo

finish

2)expand project folder

goto src/main/java

com.klu.SpringDemo-->right click new class

Student.java
App.java

App.java already exist no need to create again.

Goto src/main/java right click

Create new xml file

applicationContext.xml

3)open pom.xml

add spring context jar files dependency to xml file

----open browser

https://mvnrepository.com/

search spring context jars in website

goto Spring Context

select 5.3.20 final jar files

goto dependency jars copy from website

and paste in pom.xml file

4)goto App.java
run as Java application

Spring Demo(Hello World message)


-----------------------------------------------------------------------
Student.java
---------------------------
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo(){
System.out.println("Hello: "+name);
}

applicationContext.xml
-------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schem
a/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-instance"
xmlns:p="http://www.springframework.org/sch
ema/p"
xsi:schemaLocation="http://www.springframew
ork.org/schema/beans
http://www.springframework.org/schema/beans
/spring-beans-3.0.xsd">
<bean id="studentbean"
class="com.klu.SpringDemo.Student">
<property name="name"
value="vijay"></property>
</bean>
</beans>

App.java
----------------------------------------------------------------------

import
org.springframework.beans.factory.BeanFacto
ry;
import
org.springframework.beans.factory.xml.XmlBe
anFactory;
import
org.springframework.core.io.ClassPathResour
ce;
import
org.springframework.core.io.Resource;

public class App


{
public static void main(String[] args)
{
BeanFactory factory = new
XmlBeanFactory(new
ClassPathResource("applicationContext.xml")
);
Student
st=(Student)factory.getBean("studentbean");
st.displayInfo();
System.out.println("Hello World");
}

}
Spring Core module :
Spring IoC Container
Spring IoC stands for Inversion of Control. It is the heart of the Spring
Framework. The important tasks performed by the IoC container are:

1. Instantiating the bean


2. Wiring the beans together
3. Configuring the beans
4. Managing the bean’s entire life-cycle

The IoC container receives metadata from either an XML file, Java annotations, or
Java code and works accordingly. IoC adds the flexibility and control of
application, and provides a central place of configuration management for Plain
Old Java Objects (POJO) of our application. This diagram represents an
abstract view of the working of Spring Framework. It shows how Spring makes
use of Java POJO classes and configuration metadata to produce a fully configured
and executable system or application.

There are two types of IoC containers:

1. BeanFactory
2. ApplicationContext

BeanFactory

 It is an interface defined
in org.springframework.beans.factory.BeanFactory.
 Bean Factory provides the basic support for Dependency Injection.
 It is based on factory design pattern which creates the beans of any type.
 BeanFactory follows lazy-initialization technique which means beans are
loaded as soon as bean factory instance is created but the beans are created
only when getBean() method is called.
 The XmlBeanFactory is the implementation class for the BeanFactory
interface. To use the BeanFactory, you need to create the instance of
XmlBeanFactory class as shown below:

BeanFactory bean = new XmlBeanFactory(new


1
ClassPathResource("applicationContext.xml"));
ApplicationContext

 It is an interface
defined in org.springframework.context.ApplicationContext.
 It is the advanced Spring container and is built on top of the BeanFactory
interface.
 ApplicationContext supports the features supported by Bean Factory but
also provides some additional functionalities.
 The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. You need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as
shown below:

ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");

Dependency Injection
Dependency Injection is also one of the core concepts of Spring Framework. It is a
design pattern that removes the dependency from the code. That is, the Spring
Framework provides the dependencies of the class itself so that it can be easy to
manage and test the application. You can provide information from external source
such as XML file. Here, you do not create the objects instead you just define how
they should be created and IoC container will create the objects for you.

In Spring, dependencies can be injected in two ways:

1. By constructor
2. By setter method

By Constructor

 The <constructor-arg> subelement of <bean> is used for constructor


injection.

1 <constructor-arg value="101" type="int"></constructor-arg>


 By default when the Spring container loads the bean, it instantiates the bean
with the default constructor. But you can also define a constructor argument
in bean definition, using an argument constructor.

Steps to create MAVEN SPRING DI project in


Eclipse
----------------------------------------------------------------------------------

1)goto file->new->project->search MAVEN


select maven project
use default workspace location select
next
select org.apache.maven.archetypes maven-archetype-
quickstart version 1.1
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : springdiconstructor
finish

2)expand project folder


goto src/main/java
com.klu. springdiconstructor -->right click new class
create 2 classes
Employee.java
App.java
App.java already exist no need to create again.

Goto src/main/java right click


Create new xml file
applicationContext.xml
3)open pom.xml
add spring context jar files dependency to xml file
add spring context jar files

----open browser
https://mvnrepository.com/

search spring context jars in website


goto Spring Context
select 5.3.20 final jar files
goto dependency jars copy from website
and paste in pom.xml file
4)goto App.java
run as Java application

Example Spring DI Constructor


---------------------------
Employee.java

---------------

public class Employee {


private int id;
private String name;
public Employee(int id, String name)
{
this.id = id;
this.name = name;
}
void show()
{
System.out.println("Employee ID =
"+id);
System.out.println("Employee Name =
"+name);
}

applicationContext.xml
-----------------------

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schem
a/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-instance"
xmlns:p="http://www.springframework.org/sch
ema/p"
xsi:schemaLocation="http://www.springframew
ork.org/schema/beans
http://www.springframework.org/schema/beans
/spring-beans-3.0.xsd">
<bean id="emp_bean"
class="com.klu.springdiconstructor.Employee
">
<constructor-arg value="1002"
type="int"></constructor-arg>
<constructor-arg value="Vijay Kumar"
type="String"></constructor-arg>
</bean>
</beans>

App.java
--------------------
import
org.springframework.context.ApplicationCont
ext;
import
org.springframework.context.support.ClassPa
thXmlApplicationContext;

public class App


{
public static void main(String[] args)
{
ApplicationContext acob = new
ClassPathXmlApplicationContext("application
Context.xml");
Employee
eob=(Employee)acob.getBean("emp_bean");
eob.show();
}
}

By setter method

 The <property> subelement of <bean> is used for setter injection.e.g:

1 <property name="id" value="101"></property>


 Setter-based Dependency Injection is accomplished by the container calling
setter methods on your beans after invoking a no-argument.

Spring DI Setter method program


----------------------------------
Employee.java
--------------------
public class Employee {
private int id;
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}

private String name;

void show()
{
System.out.println("Employee ID =
"+id);
System.out.println("Employee Name =
"+name);
}

applicationContext.xml
-----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schem
a/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-instance"
xmlns:p="http://www.springframework.org/sch
ema/p"
xsi:schemaLocation="http://www.springframew
ork.org/schema/beans
http://www.springframework.org/schema/beans
/spring-beans-3.0.xsd">
<bean id="emp_bean"
class="com.klu.springdiconstructor.Employee
">
<property name="id"
value="210003001"></property>
<property name="name" value="vijay
kumar"></property>
</bean>
</beans>

App.java
--------------------------
import
org.springframework.context.ApplicationCont
ext;
import
org.springframework.context.support.ClassPa
thXmlApplicationContext;

public class App


{
public static void main(String[] args)
{
ApplicationContext acob = new
ClassPathXmlApplicationContext("application
Context.xml");
Employee
eob=(Employee)acob.getBean("emp_bean");
eob.show();
}

AOP (Aspect Oriented Programming)


Aspect-oriented programming (AOP) is a programming approach that
allows global properties of a program to determine how it is compiled into an
executable program. AOP compliments OOPs in the sense that it also provides
modularity. But here, the key unit of modularity is an aspect rather than a class.
AOP breaks down the logic of program into distinct parts called concerns. This
increases modularity by cross-cutting concerns.
A cross-cutting concern is a concern that affects the whole application and
is centralized in one location in code like transaction management, authentication,
logging, security etc. See the following diagram to understand it better.AOP can
also be considered as a dynamic decorator design pattern. The decorator pattern
allows additional behavior to be added to an existing class by wrapping the original
class and duplicating its interface and then delegating to the original. You can say
that Spring AOP hijacks the executing method, and adds extra functionality before
or after the method execution.

1. Aspect : An aspect is a class that implements the JEE application concerns


which cuts through multiple classes, such as transaction management,
security etc. Aspects can be a normal class configured through Spring XML
configuration. It can also be regular classes annotated using
@Aspect annotation.
2. Joinpoint : A joinpoint is a candidate point in the program execution of an
application where an aspect can be plugged in. This point could be a method
being called, an exception being thrown, or even a field being modified.
3. Advice: Advices are the actual actions taken for a particular
joinpoint. Basically, they are the methods that get executed when a certain
joinpoint meets a matching pointcut in the application.
4. Pointcut: Pointcut are expressions that are matched with join points to
determine whether advice needs to be executed or not.
5. Target Object: They are the object on which advices are applied. In Spring
AOP, a subclass is created at runtime where the target method is overridden
and advices are included based on their configuration.
6. Proxy: A proxy is an object that is created after applying advice to the target
object. In terms of client, the objects, the target object and the proxy object
are same.
7. Weaving: Weaving is the process of linking an aspect with other application
types or objects to create an advised object.

AOP Advice Types

 Before: These types of advices execute before the joinpoint methods. They
are configured using @Before annotation mark.
 After returning: These types of advices execute after the joinpoint methods
complete executing normally. They are configured using
@AfterReturning annotation mark.
 After throwing: These types of advices execute only when joinpoint
method exits by throwing an exception. They are configured using
@AfterThrowing annotation mark.
 After (finally): These types of advices execute after a joinpoint method
executes, regardless of the method’s exit (whether normal or exceptional
return). They are configured using @After annotation mark.
 Around: These types of advices execute before and after a join point and are
configured using @Around annotation mark.

SPRING ANNOTATION
Spring Annotations are a form of metadata that provides data about a
program. Annotations are used to provide supplemental information
about a program. It does not have a direct effect on the operation of
the code they annotate. It does not change the action of the compiled
program.

Spring Core Annotations

Spring web Annotations

Spring Boot Annotations

Spring Bean Annotations.

Annotations are present in


org.springframework.beans.factory.annotation.

@Autowired

@Bean

@Required

@Value
@Configuration

Spring Annotations example


----------------------------------------------
Hello.java
-----------------------------------
package com.klu.springannotation;
interface HelloInt {
void show();
}
public class Hello implements
HelloInt{
public void show()
{
System.out.println("hello
spring annotation");
}
}
HelloConfig.java
---------------------------------------------------------
package com.klu.springannotation;
import
org.springframework.context.annotat
ion.Bean;
import
org.springframework.context.annotat
ion.Configuration;
import
org.springframework.context.annotat
ion.Description;

@Configuration
public class HelloConfig {
@Bean(name="hellobean")
public HelloInt helloint() {
return new Hello();
}
}

App.java
-------------------------------------------
package com.klu.springannotation;

import
org.springframework.context.annotat
ion.AnnotationConfigApplicationCont
ext;
import
org.springframework.context.support
.AbstractApplicationContext;

public class App


{
public static void main(String
args[]) {
AbstractApplicationContext
context = new
AnnotationConfigApplicationContext(
HelloConfig.class);
Hello bean = (Hello)
context.getBean("hellobean");
bean.show();
context.close();
}
}
Spring – Autowiring
Spring is an open-source application development framework of Java
that allows you to create Enterprise applications using Plain Old Java
Objects (POJO). The Spring framework can inject dependencies
automatically. The Spring container detects those dependencies
specified in the configuration file and @ the relationship between the
beans. This is referred to as autowiring in Spring.
Types of autowiring
no: This mode tells the framework that autowiring is not supposed to
be done. It is the default mode used by Spring.
byName
It uses the name of the bean for injecting dependencies. However, it
requires that the name of the property and bean must be the same. It
invokes the setter method internally for autowiring.
byType
It injects the dependency according to the type of the bean. It looks
up in the configuration file for the class type of the property.
constructor
It injects the required dependencies by invoking the constructor. It
works similar to the “byType” mode but it looks for the class type of
the constructor arguments.
autodetect
The autodetect mode uses two other modes for autowiring –
constructor and byType. It first tries to autowire via the constructor
mode and if it fails, it uses the byType mode for autowiring. It works
in Spring 2.0 and 2.5 but is deprecated from Spring 3.0 onwards.

Advantage of Autowiring
It requires less code because we don’t need to write the code to inject
the dependency explicitly.

Disadvantage of Autowiring

 No control of the programmer.


 It can’t be used for primitive and string values.

SPRING AUTOWIRING EXAMPLE


----------------------------------------
Employee.java
---------------------------

package com.klu.springautowiring;

public class Employee {

private String name;

public String getName() {


return name;
}

public void setName(String name)


{
this.name = name;
}
}

EmployeeService.java
-------------------------
package com.klu.springautowiring;
public class EmployeeService {

private Employee employee;

/*constructor is used for


autowire by constructor
public EmployeeService(Employee
emp) {
System.out.println("Autowiring
by constructor used");
this.employee = emp;
}

// default constructor to avoid


BeanInstantiationException for
autowire
// byName or byType
public EmployeeService() {
System.out.println("Default
Constructor used");
}*/

// used for autowire byName and


byType
public void setEmployee(Employee
emp) {
this.employee = emp;
}

public Employee getEmployee() {


return this.employee;
}
}

EmployeeAutowiredByTypeService.java
-----------------------------------
---
package com.klu.springautowiring;

import
org.springframework.beans.factory.a
nnotation.Autowired;

public class
EmployeeAutowiredByTypeService {
//Autowired annotation on
variable/setters is equivalent to
autowire="byType"
@Autowired
private Employee employee;
@Autowired
public void setEmployee(Employee
emp){
this.employee=emp;
}
public Employee getEmployee(){
return this.employee;
}
}

App.java
---------------------------

package com.klu.springautowiring;
import
org.springframework.context.support
.ClassPathXmlApplicationContext;
public class App
{
public static void main(String[]
args) {
ClassPathXmlApplicationContext
ctx = new
ClassPathXmlApplicationContext("app
licationContext.xml");
EmployeeService serviceByName
=
ctx.getBean("employeeServiceByName"
, EmployeeService.class);

System.out.println("Autowiring
byName. Employee
Name="+serviceByName.getEmployee().
getName());
EmployeeService serviceByType
=
ctx.getBean("employeeServiceByType"
, EmployeeService.class);

System.out.println("Autowiring
byType. Employee
Name="+serviceByType.getEmployee().
getName());

//Testing @Autowired
annotations
EmployeeAutowiredByTypeService
autowiredByTypeService =
ctx.getBean("employeeAutowiredByTyp
eService",EmployeeAutowiredByTypeSe
rvice.class);

System.out.println("@Autowired
byType. Employee
Name="+autowiredByTypeService.getEm
ployee().getName());

ctx.close();
}
}
applicationContext.xml
-----------------------------------
-
<?xml version="1.0" encoding="UTF-
8"?>
<beans
xmlns="http://www.springframework.o
rg/schema/beans"
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns:p="http://www.springframework
.org/schema/p"
xsi:schemaLocation="http://www.spri
ngframework.org/schema/beans
http://www.springframework.org/sche
ma/beans/spring-beans-3.0.xsd">
<bean name="employee"
class="com.klu.springautowiring.Emp
loyee">
<property name="name"
value="vijay"></property>
</bean>

<bean name="employee1"
class="com.klu.springautowiring.Emp
loyee" autowire-candidate="false">
<property name="name"
value="Dummy Name"></property>
</bean>

<!-- autowiring byName, bean name


should be same as the property name
-->
<bean name="employeeServiceByName"
class="com.klu.springautowiring.Emp
loyeeService" autowire="byName" />

<!-- autowiring byType, there


should be only one bean definition
for the mapping -->
<bean name="employeeServiceByType"
class="com.klu.springautowiring.Emp
loyeeService" autowire="byType" />
<!-- using @Autowiring annotation
in below beans, byType and
constructor -->
<bean
name="employeeAutowiredByTypeServic
e"
class="com.klu.springautowiring.Emp
loyeeAutowiredByTypeService" />
</beans>

Spring - JDBC/DAO (Data Access Object):


--------------------

-> It is used to build Data Access Layer of Enterprise Applications

-> It is a mechanism to connect to the d/b and execute SQL queries.

-> The database related logic has to placed in seperate classes called DAO Classes.

limitation of JDBC

-------------------------------------------------

-> JDBC exceptions are "checked" excpeitons, so we must use try/catch or throws
at various places in the code
-> this will increase the comlexity of the applications

-> Connection must be closed by user explicitly, if not we may get some issues
with connection.

JdbcTemplate (class) in Spring JDBC:


-------------------------------------------------

-> JdbcTempalte - is a class

-> it is given by " org.springframework.jdbc.core.*" package

-> this class provides method to execute SQL commands on d/b.

-> JdbcTemplate class follows TEMPLATE Design Pattern,

-> Template class accepts i/p from user,

produces o/p to the user,

hides the internal details.

-> methods are:

execute() is select & non-select operations

update() is non-select operation

query() is for select operation.


Steps to create MAVEN SPRING JDBC project
in Eclipse
----------------------------------------------------------------------------------

1)goto file->new->project->search MAVEN


select maven project
use default workspace location select
next
select org.apache.maven.archetypes maven-archetype-
quickstart version 1.1
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : springjdbc
finish

2)expand project folder


goto src/main/java
com.klu.springjdbc-->right click new class
create 2 classes
Employee.java
EmployeeDAO.java
App.java
App.java already exist no need to create again.

Goto src/main/java right click


Create new xml file
applicationContext.xml
3)open pom.xml
add spring context jar files dependency to xml file
add spring DAO jar files
add oracle(ojdbc8) jar file
add spring JDBC jar file

----open browser
https://mvnrepository.com/

search spring context jars in website


goto Spring Context
select 5.3.20 final jar files
goto dependency jars copy from website
and paste in pom.xml file
spring jdbc-select 5.3.20jar files
oracle ojdbc8-select 12.2.0.1 jar files
spring dao-select 2.0.3 jar files
4)goto App.java
run as Java application

SPRING JDBC EXAMPLE


---------------------------------------

Employee.java
----------------------

public class Employee {


public Employee() {
super();
// TODO Auto-generated constructor
stub
}
private int id;
private String name;
private int salary;

public Employee(int id, String name,


int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

EmployeeDAO.java
import
org.springframework.jdbc.core.JdbcTemplate;

public class EmployeeDAO {


private JdbcTemplate jdbcTemplate;

public JdbcTemplate getJdbcTemplate() {


return jdbcTemplate;
}

public void
setJdbcTemplate(JdbcTemplate jdbcTemplate)
{
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
String query="insert into
employee345 values('"+e.getId()
+"','"+e.getName()+"','"+e.getSalary()
+"')";
return jdbcTemplate.update(query);
}
/*public int updateEmployee(Employee e)
{
String query="update employee345
set name='"+e.getName()
+"',salary='"+e.getSalary()+"' where
id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
} */
/*public int deleteEmployee(Employee e)
{
String query="delete from
employee345 where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
} */

App.java
------------------------
import
org.springframework.context.ApplicationCont
ext;
import
org.springframework.context.support.ClassPa
thXmlApplicationContext;

public class App


{
public static void main(String[] args){
System.out.println("testing...");
// TODO Auto-generated method stub
ApplicationContext acob
= new
ClassPathXmlApplicationContext("application
Context.xml");

EmployeeDAO
dao=(EmployeeDAO)acob.getBean("edao");
int status=dao.saveEmployee(new
Employee(101,"vijay",3500));
System.out.println("Successfully
saved");
/*int status=dao.updateEmployee(new
Employee(101,"kumar",15000));
System.out.println("Successfully
updated"); */

/*Employee e=new Employee();


e.setId(101);
int status=dao.deleteEmployee(e);
System.out.println("Successfully
deleted"); */

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schem
a/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-instance"
xmlns:p="http://www.springframework.org/sch
ema/p"
xsi:schemaLocation="http://www.springframew
ork.org/schema/beans
http://www.springframework.org/schema/
beans/spring-beans-3.0.xsd">
<bean id="ds"
class="org.springframework.jdbc.datasource.
DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"
/>
<property name="username" value="system" />
<property name="password" value="vijay" />
</bean>

<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTe
mplate">
<property name="dataSource"
ref="ds"></property>
</bean>
<bean id="edao"
class="com.klu.springjdbc.EmployeeDAO">
<property name="jdbcTemplate"
ref="jdbcTemplate"></property>
</bean>
</beans>

Spring JDBC Dependencies


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.spri
ngframework/spring-dao -->
<!--
https://mvnrepository.com/artifact/org.spri
ngframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.3</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.orac
le.database.jdbc/ojdbc8 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.spri
ngframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.20</version>
</dependency>

In sql commandline
SQL> create table employee345(id number(6),name
varchar2(20),salary number(10));

Table created.

SQL> desc employee345;


Spring MVC
The Spring Web MVC framework provides Model-View-Controller (MVC)
architecture.

It has built-in components that can be used to develop flexible and


loosely coupled web applications.

The MVC pattern results in separating the different aspects of the


application (input logic, business logic, and UI logic), while providing a
loose coupling between these elements.

It follows Model - View - Controller design Pattern,

Model:

 a model contains the data of the applications.


 a data can be single object or collection of objects.
 The Model encapsulates the application data and in general
they will consist of POJO.
View:

 a view represents the information in a particular format.


 JSP + JSTL is used to create a view page.
 The View is responsible for rendering the model data and in
general it generates HTML output
Controller:

 a controller contains the business logic of the applications.


 The Controller is responsible for processing user requests
and building an appropriate model and passes it to the view
for rendering.
 In spring MVC, DispatcherServlet class works as the front
controller.

 DispatcherServlet Class receives the incoming requests and


maps it to the resource such as Controllers, Models, and
Views.
 Dispatcher Servlet gets an entry of handler mapping from
XML file and forwards the request to the controller.

SPRING MVC EXAMPLE

-----------------------------------------------------
---------------------------------------------------------

steps:

--------

1) controller

create HelloWorldController.java

2)View

create index.jsp

3) Mapping spring mvc in web.xml

create web.xml

4)spring configuration

create spring-servlet.xml

----we have defined a tag <context:component-scan>.

This will allow Spring to load all the components from

package SpringMVCDemo and all its child packages.

This will load our HelloWorldController class.

5)add jar files


Steps to create SPRING MVC Demo project in
Eclipse
------------------------------------------------
File->new->Dynamic Web Project->springmvc->next

Select Generate web.xml deployment descriptor ->Finish

CONVERT DYNAMIC WEB PROJECT TO MAVEN PROJECT

Project(springmvc)->configure->Convert to Maven Project

Group Id : com.klu

Artifact Id : springmvcdemo

Packaging : war

Name : springmvcdemo

Description : springmvcdemo

Finish

Open POM.XML add dependencies

------------------------------------
<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.3.9.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>4.3.9.RELEASE</version>

</dependency>

<!-- Servlet -->

<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>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

</dependencies>

Open WEB.XML in WebContent->WEB-INF->lib


---------------------------------

<?xml version="1.0" encoding="UTF-


8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j
avaee"
xsi:schemaLocation="http://java.sun
.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/w
eb-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-
name>springmvcdemo</display-name>
<welcome-file-list>
<welcome-
file>index.html</welcome-file>
<welcome-
file>index.htm</welcome-file>
<welcome-
file>index.jsp</welcome-file>
<welcome-
file>default.html</welcome-file>
<welcome-
file>default.htm</welcome-file>
<welcome-
file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-
name>spring</servlet-name>
<servlet-class>

org.springframework.web.servlet.Dis
patcherServlet
</servlet-class>
<load-on-startup>1</load-on-
startup>
</servlet>
<servlet-mapping>
<servlet-
name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Goto WEB-INF ->new xml file


Spring-servlet.xml
--------------------------------------

<?xml version="1.0" encoding="UTF-


8"?>
<beans
xmlns="http://www.springframework.o
rg/schema/beans"
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns:p="http://www.springframework
.org/schema/p"
xmlns:context="http://www.springfra
mework.org/schema/context"
xsi:schemaLocation="http://www.spri
ngframework.org/schema/beans

http://www.springframework.org/sche
ma/beans/spring-beans-3.0.xsd

http://www.springframework.org/sche
ma/context

http://www.springframework.org/sche
ma/context/spring-context-3.0.xsd">

<context:component-scan base-
package="springmvcdemo" />
</beans>
Goto Java Resources
src ->rightclick new package
springmvcdemo
springmvcdemo package ->right click new class
HelloWorldController.java
-------------------------------

package springmvcdemo;

import
org.springframework.stereotype.Cont
roller;
import
org.springframework.web.bind.annota
tion.RequestMapping;
//import
org.springframework.web.servlet.Mod
elAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/")
public String display()
{
return "index";
}
}

Goto WebContent -> new JSP file


Index.jsp
------------------------------------

<%@ page language="java"


contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<p>Welcome to Spring MVC</p>
</body>

</html>

Open index.jsp
Run as Run on Server
Add Tomcat server
Finish
Steps to create SPRING MVC with JDBC
project in Eclipse
------------------------------------------------
File->new->Dynamic Web Project->springmvcjdbc->next

Select Generate web.xml deployment descriptor ->Finish

CONVERT DYNAMIC WEB PROJECT TO MAVEN PROJECT

Project(springmvcjdbc)->configure->Convert to Maven Project

Group Id : springmvcjdbc

Artifact Id : springmvcjdbc

Finish

Open POM.XML add dependencies


------------------------------------

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</
groupId>
<artifactId>spring-webmvc</
artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
org.apache.tomcat/tomcat-jasper --
>
<dependency>
<groupId>org.apache.tomcat</
groupId>
<artifactId>tomcat-jasper</
artifactId>
<version>9.0.12</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
javax.servlet/javax.servlet-api --
>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</
artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
com.oracle.database.jdbc/ojdbc8 -->
<dependency>
<groupId>com.oracle.database.jdbc</
groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

<!--
https://mvnrepository.com/artifact/
org.springframework/spring-jdbc --
>
<dependency>
<groupId>org.springframework</
groupId>
<artifactId>spring-jdbc</
artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
</dependencies>

Open WEB.XML in WebContent->WEB-INF->lib


---------------------------------

<?xml version="1.0" encoding="UTF-


8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j
avaee"
xsi:schemaLocation="http://java.sun
.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/w
eb-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-
name>springmvcjdbc</display-name>
<servlet>
<servlet-name> s1 </servlet-
name>
<servlet-class>
org.springframework.web.servlet.Dis
patcherServlet </servlet-class>
<init-param>
<param-
name>contextConfigLocation</param-
name>
<param-
value>/WEB-INF/spring-
servlet.xml</param-value>
</init-param>
<load-on-startup> 100 </load-on-
startup>
</servlet>
<servlet-mapping>
<servlet-name> s1 </servlet-
name>
<url-pattern> / </url-pattern>
</servlet-mapping>
</web-app>

Goto WEB-INF ->new xml file


spring-servlet.xml
--------------------------------------

<?xml version="1.0" encoding="UTF-


8"?>
<beans
xmlns="http://www.springframework.o
rg/schema/beans"
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns:p="http://www.springframework
.org/schema/p"
xmlns:context="http://www.springfra
mework.org/schema/context"
xsi:schemaLocation="http://www.spri
ngframework.org/schema/beans
http://www.springframework.org/
schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/
schema/context
http://www.springframework.org/
schema/context/spring-context-
3.0.xsd">

<context:component-scan base-
package="springmvcjdbc"></context:c
omponent-scan>

<bean
class="org.springframework.web.serv
let.view.InternalResourceViewResolv
er">
<property name="prefix" value =
"/WEB-INF/views/"></property>
<property name="suffix" value =
".jsp"></property>
</bean>
<bean id="ds"
class="org.springframework.jdbc.dat
asource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDri
ver" />
<property name="url"
value="jdbc:oracle:thin:@localhost:
1521:xe" />
<property name="username"
value="system" />
<property name="password"
value="vijay" />
</bean>

<bean id="jt" class =


"org.springframework.jdbc.core.Jdbc
Template">
<property name="dataSource" ref
= "ds"></property>
</bean>

<bean id="dao" class =


"springmvcjdbc.DAO">
<property name="jdbcTemplate"
ref = "jt"></property>
</bean>

</beans>

Goto Java Resources


src ->rightclick new package
springmvcjdbc
springmvcjdbc package ->right click new class

Employee.java
----------------------------------

public class Employee {


private int eno;
private String ename;
public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String
ename) {
this.ename = ename;
}
public Employee() {
super();
// TODO Auto-generated
constructor stub
}
public Employee(int eno, String
ename) {
super();
this.eno = eno;
this.ename = ename;
}
}

DAO.java
----------------------
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import
org.springframework.jdbc.core.BeanP
ropertyRowMapper;
import
org.springframework.jdbc.core.JdbcT
emplate;
import
org.springframework.jdbc.core.RowMa
pper;
public class DAO {
JdbcTemplate jdbcTemplate;

public JdbcTemplate
getJdbcTemplate() {
return jdbcTemplate;
}

public void
setJdbcTemplate(JdbcTemplate
jdbcTemplate) {
this.jdbcTemplate =
jdbcTemplate;
}
public int insert(Employee e) {
String sql = "insert into
employee values (" + e.getEno() +
", '" + e.getEname() + "')";
return
jdbcTemplate.update(sql);
}
public int update(Employee e) {
String sql = "update employee
set ename = '" + e.getEname() + "'
where eno = " + e.getEno() + "";
return
jdbcTemplate.update(sql);
}
public int delete(int id) {
String sql = "delete from
employee where eno = " + id + "";
return
jdbcTemplate.update(sql);
}
public Employee
getEmployeeById(int id) {
String sql = "select * from
employee where eno = ?";
return
jdbcTemplate.queryForObject(sql,
new Object[]{id}, new
BeanPropertyRowMapper<Employee>(Emp
loyee.class));
}
public List<Employee>
getAllEmployees() {
String sql = "select * from
employee";
return
jdbcTemplate.query(sql, new
RowMapper<Employee>() {
public Employee
mapRow(ResultSet rs, int row)
throws SQLException {
Employee e = new
Employee();
e.setEno(rs.getInt(1));
e.setEname(rs.getString(2));
return e;
}
});
}

AppController.java
import java.util.List;
import
org.springframework.beans.factory.a
nnotation.Autowired;
import
org.springframework.stereotype.Cont
roller;
import
org.springframework.ui.Model;
import
org.springframework.web.bind.annota
tion.GetMapping;
import
org.springframework.web.bind.annota
tion.ModelAttribute;
import
org.springframework.web.bind.annota
tion.PathVariable;
import
org.springframework.web.bind.annota
tion.PostMapping;

@Controller
public class AppController {
@Autowired
DAO dao;
@GetMapping("/show")
public String show (Model m) {
List<Employee> l =
dao.getAllEmployees();
m.addAttribute("list", l);
return "show";
}
@GetMapping("/edit/{id}")
public String edit
(@PathVariable("id") int id, Model
m) {
Employee s =
dao.getEmployeeById(id);
m.addAttribute("command", s);
return "edit";
}
@PostMapping("/editsave")
public String editsave
(@ModelAttribute("e") Employee e) {
int r = dao.update(e);
return "redirect:/show";
}
@GetMapping("/delete/{id}")
public String delete
(@PathVariable("id") int id) {
int r = dao.delete(id);
return "redirect:/show";
}
@GetMapping("/add")
public String add (Model m) {
m.addAttribute("command", new
Employee());
return "add";
}
@PostMapping("/addsave")
public String addsave
(@ModelAttribute("e") Employee e) {
int r = dao.insert(e);
return "redirect:/show";
}

}
Goto WebContent -> new JSP file
index.jsp
------------------------------------

<%@ page language="java"


contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<body>
<h2>Welcome to </h2>
<a href="/springmvcjdbc/add"> Add
Employee </a>
<a href="/springmvcjdbc/show"> Show
Employees </a>
</body>
</html>

WEB-INF Right Click create new folder views


views right click create 3 jsp files

add.jsp
--------------------------
<%@ page language="java"
contentType="text/html;
charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ taglib
uri="http://www.springframework.org
/tags/form" prefix="form" %>
<%@ taglib
uri="http://java.sun.com/jsp/jstl/c
ore" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
</head>
<body>
<h1> Add Employee </h1>
<form method="post"
action="/springmvcjdbc/addsave">
ID: <input path="eno"/>
NAME: <input path="ename"/>
<input type="submit"
value="save" />
</form>
</body>
</html>

edit.jsp
--------------------
<%@ page language="java"
contentType="text/html;
charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ taglib
uri="http://www.springframework.org
/tags/form" prefix="form" %>
<%@ taglib
uri="http://java.sun.com/jsp/jstl/c
ore" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Employee</title>
</head>
<body>
<h1> Edit Employee </h1>
<form:form method="post"
action="/springmvcjdbc/editsave">
ID: <form:input path="eno"/>
NAME: <form:input path="ename"/>
<input type="submit"
value="editsave" />
</form:form>
</body>
</html>

show.jsp
----------------------------
<%@ page isELIgnored="false"
language="java"
contentType="text/html;
charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ taglib
uri="http://www.springframework.org
/tags/form" prefix="form" %>
<%@ taglib
uri="http://java.sun.com/jsp/jstl/c
ore" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Show Employees</title>
</head>
<body>
<table>
<tr>
<th>ENO</th>
<th>ENAME</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>

<c:forEach var="s" items="${list}">


<tr>
<td>${s.eno}</td>
<td>${s.ename}</td>
<td><a href="/springmvcjdbc/edit/$
{s.eno}">EDIT</a></td>
<td><a
href="/springmvcjdbc/delete/$
{s.eno}">DELETE</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Open Run SQL CommandLine


connect system/vijay
create table employee(eno number,ename
varchar2(20));
desc employee;

Open index.jsp
Run as Run on Server
Add Tomcat server
Finish

SPRING with HIBERNATE project in Eclipse

1)goto file->new->project->search MAVEN


select maven project
use default workspace location select
next
select org.apache.maven.archetypes maven-archetype-
quickstart version 1.1
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu

Artifact id : springhibernate
finish

2)expand project folder


goto src/main/java
com.klu.springhibernate-->right click new class
create 3 classes
Employee.java
EmployeeDAO.java
EmployeeController.java
Open WEB.XML in WebContent->WEB-INF->lib

Goto WEB-INF ->new xml file


hiberspring-servlet.xml
src/main/java right click new xml
Employee.hbm.xml

Goto WebContent -> new JSP file


index.jsp
WEB-INF Right Click create new folder views
views right click create 3 jsp files

add.jsp
edit.jsp
show.jsp

3)open pom.xml
Add required jar files

----open browser
https://mvnrepository.com/

4)goto index.jsp
run as run on server

Employee.java
---------------
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double
salary) {
this.salary = salary;
}
public Employee() {
super();
}
public Employee(int id, String
name, int age, double salary) {
this.age = age;
this.id = id;
this.name = name;
this.salary = salary;
}
}

import
org.springframework.beans.factory.a
nnotation.Autowired;
import
org.springframework.stereotype.Cont
roller;
import
org.springframework.ui.Model;
import
org.springframework.web.bind.annota
tion.GetMapping;
import
org.springframework.web.bind.annota
tion.ModelAttribute;
import
org.springframework.web.bind.annota
tion.PathVariable;
import
org.springframework.web.bind.annota
tion.PostMapping;

EmployeeController.java
----------------------------
@Controller
public class EmployeeController {

@Autowired
EmployeeDAO daoimp;

@GetMapping("/add")
public String add(Model m) {
m.addAttribute("command", new
Employee());
return "add";
}
@PostMapping("/save")
private String
save(@ModelAttribute("s") Employee
s) {
daoimp.insert(s);
return "redirect:/show";
}
@GetMapping("/show")
public String show(Model m) {
m.addAttribute("emplist",
daoimp.getAllDetails());
return "show";
}
@GetMapping("/edit/{id}")
public String
edit(@PathVariable("id") int id,
Model m) {
Employee e =
daoimp.getEmployeeById(id);
m.addAttribute("command", e);
return "edit";
}
@PostMapping("/editsave")
public String
update(@ModelAttribute("s")
Employee s) {
daoimp.update(s);
return "redirect:/show";
}
@GetMapping("/delete/{id}")
public String
delete(@PathVariable("id") int id)
{
daoimp.delete(id);
return "redirect:/show";
}
}

import java.util.List;

import
org.springframework.orm.hibernate3.
HibernateTemplate;

EmployeeDAO.java
public class EmployeeDAO {
HibernateTemplate template;
public HibernateTemplate
getTemplate() {
return template;
}

public void
setTemplate(HibernateTemplate
template) {
this.template = template;
}
public void insert(Employee
employee) {
template.save(employee);
}
public void update(Employee
employee) {
template.update(employee);
}
public Employee
getEmployeeById(int id) {
return (Employee)
template.get(Employee.class,id);
}
public void delete(int id) {
Employee e =
getEmployeeById(id);
template.delete(e);
}
@SuppressWarnings("unchecked")
public List<Employee>
getAllDetails() {
return
(List<Employee>)template.find("from
Employee");
}
}

Pom.xml
-------------------------------
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>

<groupId>org.springframework</group
Id>
<artifactId>spring-
webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>

<!--
https://mvnrepository.com/artifact/
org.apache.tomcat/tomcat-jasper -->
<dependency>

<groupId>org.apache.tomcat</groupId
>
<artifactId>tomcat-
jasper</artifactId>
<version>9.0.12</version>
</dependency>

<!--
https://mvnrepository.com/artifact/
javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-
api</artifactId>
<version>3.0-alpha-
1</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/
com.oracle.database.jdbc/ojdbc8 -->
<dependency>
<groupId>com.oracle.database.jdbc</
groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

<dependency>

<groupId>javax.transaction</groupId
>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>

<!--

https://mvnrepository.com/artifact/
org.springframework/spring-
hibernate3 -->
<dependency>

<groupId>org.springframework</group
Id>
<artifactId>spring-
hibernate3</artifactId>
<version>2.0.8</version>
</dependency>

<!--
https://mvnrepository.com/artifact/
commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-
dbcp</groupId>
<artifactId>commons-
dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<!--
https://mvnrepository.com/artifact/
org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-
core</artifactId>
<version>5.3.1.Final</version>
</dependency>

</dependencies>

Web.xml
-------------------------------
<?xml version="1.0" encoding="UTF-
8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j
avaee"
xsi:schemaLocation="http://java.sun
.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/w
eb-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-
name>springhibernate</display-name>
<servlet>
<servlet-
name>springhibernate</servlet-name>
<servlet-
class>org.springframework.web.servl
et.DispatcherServlet</servlet-
class>
<init-param>
<param-
name>contextConfigLocation</param-
name>
<param-value>/WEB-
INF/hiberspring-servlet.xml</param-
value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-
name>springhibernate</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hiberspring-servlet.xml
-------------------------------
<?xml version="1.0" encoding="UTF-
8"?>
<beans
xmlns="http://www.springframework.o
rg/schema/beans"
xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xmlns:p="http://www.springframework
.org/schema/p"
xmlns:context="http://www.springfra
mework.org/schema/context"
xsi:schemaLocation="http://www.spri
ngframework.org/schema/beans
http://www.springframework.org/
schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/
schema/context
http://www.springframework.org/
schema/context/spring-context-
3.0.xsd">

<context:component-scan base-
package="springhibernate"></context
:component-scan>

<bean
class="org.springframework.web.serv
let.view.InternalResourceViewResolv
er">
<property name="prefix" value =
"/WEB-INF/views/"></property>
<property name="suffix" value =
".jsp"></property>
</bean>

<bean id="ds"
class="org.springframework.jdbc.dat
asource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDri
ver" />
<property name="url"
value="jdbc:oracle:thin:@localhost:
1521:xe" />
<property name="username"
value="system" />
<property name="password"
value="vijay" />
</bean>
<bean id="sf"
class="org.springframework.orm.hibe
rnate3.LocalSessionFactoryBean">
<property name="dataSource"
ref="ds"/>
<property
name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property
name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hiberna
te.dialect.OracleDialect</prop>
<prop
key="hibernate.hbm2ddl.auto">update
</prop>
<prop
key="hibernate.show_sql">true</prop
>
</props>
</property>
</bean>

<bean id="template"
class="org.springframework.orm.hibe
rnate3.HibernateTemplate">
<property
name="sessionFactory"
ref="sf"></property>
</bean>

<bean id="daoimp" class =


"springhibernate.EmployeeDAO">
<property name="template" ref =
"template"></property>
</bean>

</beans>

Goto WEB-INF right click new folder views


views right click create new jsp
add.jsp
edit.jsp
show.jsp

add.jsp
<%@ page language="java"
contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">Add Employee
Details</h1>
<form
action="/springhibernate/save"
method="post">
<label path="id">Employee
ID</label>
<input path="id"/>
<label path="name">Employee
Name</label>
<input path="name"/>
<label path="age">Age</label>
<input path="age"/>
<label path="salary">Salary</label>
<input path="salary"/>
<input type="submit"
value="Insert"/>

</form>
</body>
</html>

edit.jsp
<%@ page language="java"
contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">Edit Employee
Details</h1>
<form:form
action="/springhibernate/editsave"
method="post">
<form:label path="id">Employee
ID</form:label>
<form:input path="id"/>
<form:label path="name">Employee
Name</form:label>
<form:input path="name"/>
<form:label
path="age">Age</form:label>
<form:input path="age"/>
<form:label
path="salary">Salary</form:label>
<form:input path="salary"/>
<input type="submit"
value="Update"/>

</form:form>
</body>
</html>

show.jsp
<%@ page language="java"
contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<th>Emp ID</th>
<th>Emp Name</th>
<th>Age</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="emp" items="$
{emplist}">

<tr>
<th>${emp.id }</th>
<th>${emp.name }</th>
<th>${emp.age }</th>
<th>${emp.salary }</th>
<th><a
href="/springhibernate/edit/$
{emp.id }">Edit</a></th>
<th><a
href="/springhibernate/delete/$
{emp.id }">Delete</a></th>
</tr>

</c:forEach>

</table>
</body>
</html>

WebContent right click create new


jsp
Index.jsp
index.jsp
<%@ page language="java"
contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>EMS</h2>
<a href="add">Add
Employee</a>&#32;&#32;&#32;&#32;&#3
2;<a href="show">Show Employees</a>
</body>
</html>

Employee.hbm.xml
<?xml version="1.0" encoding="UTF-
8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="springhibernate.Employee">
<id name="id">
</id>
<property
name="name"></property>
<property
name="age"></property>
<property
name="salary"></property>
</class>
</hibernate-mapping>

Open Run SQL Commandline


-----------------------------------
-
connect system/vijay
create table Employee(id
number,name varchar2(20),age
number,salary float);
desc Employee;

You might also like