Spring Notes & Programs
Spring Notes & Programs
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.
Container: Spring Framework creates and manages the life cycle and
configuration of application objects.
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.
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
Instrumentation
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..
P
ORM
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.
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.
Right click on src > New > Other > XML File
The <bean> tag is used to define the bean for the given class.
----------------------------------------------------------------------------------
next
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : SpringDemo
finish
goto src/main/java
Student.java
App.java
applicationContext.xml
3)open pom.xml
----open browser
https://mvnrepository.com/
4)goto App.java
run as Java application
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;
}
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:
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.
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:
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.
1. By constructor
2. By setter method
By Constructor
----open browser
https://mvnrepository.com/
---------------
applicationContext.xml
-----------------------
App.java
--------------------
import
org.springframework.context.ApplicationCont
ext;
import
org.springframework.context.support.ClassPa
thXmlApplicationContext;
By setter method
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;
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.
@Autowired
@Bean
@Required
@Value
@Configuration
@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;
Advantage of Autowiring
It requires less code because we don’t need to write the code to inject
the dependency explicitly.
Disadvantage of Autowiring
package com.klu.springautowiring;
EmployeeService.java
-------------------------
package com.klu.springautowiring;
public class EmployeeService {
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>
-> 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.
----open browser
https://mvnrepository.com/
Employee.java
----------------------
EmployeeDAO.java
import
org.springframework.jdbc.core.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;
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"); */
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>
In sql commandline
SQL> create table employee345(id number(6),name
varchar2(20),salary number(10));
Table created.
Model:
-----------------------------------------------------
---------------------------------------------------------
steps:
--------
1) controller
create HelloWorldController.java
2)View
create index.jsp
create web.xml
4)spring configuration
create spring-servlet.xml
Group Id : com.klu
Artifact Id : springmvcdemo
Packaging : war
Name : springmvcdemo
Description : springmvcdemo
Finish
------------------------------------
<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>
<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>
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>
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";
}
}
</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
Group Id : springmvcjdbc
Artifact Id : springmvcjdbc
Finish
<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>
<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>
</beans>
Employee.java
----------------------------------
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
------------------------------------
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>
Open index.jsp
Run as Run on Server
Add Tomcat server
Finish
Artifact id : springhibernate
finish
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>
</beans>
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>
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>