You are on page 1of 101

Spring JDBC:

—-------------
In Enterprise Applications we have to prepare the DAO layer in order to
perform database operations, where to perform database operations in the DAO
layer we have to use Spring-JDBC.

Q)To prepare the DAO layer in an enterprise application, already we have


Plain JDBC Then what is the requirement to use Spring-JDBC?
—---------------------------------------------------------------------------
Ans:
—---
1. To perform database operations if we use plain jdbc then we have to use
the following steps.
a. Load And Register Driver:
Class.forName(“com.mysql.cj.jdbc.Driver”);

b. Establish Connection between Java application and Database:


Connection con =
DriverManager.getConnection(“jdbc:mysql://localhost:3306/durgadb”,
“root”, “root”);

c. Create Statement / PreparedSTatement / CallableStatement as per the


requirement:
Statement st = con.createStatement();

d. Write and Execute sql queries:


int rowCount = st.executeUpdate(“insert…..”);
Or
ResultSet rs = st.executeQuery(“select * from emp1”);

e. Close the resources:


rs.close();
st.close();
con.close();

To perform database operations if we use Spring-JDBC module then it is not


required to write all the above boilerplate code[Repeatable Code], just it is
required to provide only write and execute sql queries.
Note: In Spring JDBC module, all the boilerplate code is abstracted with
XXXTemplate classes like JdbcTemplate class.
Note: In JDBC, the steps like load and Register the Driver, Establish
Connection between java application and Database, Create Statement and close
the resources are called Boilerplate code.
2. In plain JDBC, when we execute a select sql query all the generated
results will come in the form of “ResultSet” object, it is not Serializable,
it is not possible to send ResultSet object in the network, in this context
if we want to send the generated results to the network then we have to
create a Collection object, we have to copy the data from ResultSet object to
the Bean object and we have to add these bean objects to the COllection
object and we have to send the generated Collection object to the network.

In the case of the Spring-JDBC module, we are able to get all the results in
the form of Collections directly, where Collection objects are Serializable
bydefault, so we are able to transfer Collection objects in the network.

3. Plain JDBC is able to provide limited support for Transactions.

Spring-JDBC module is providing very good support for Transactions with the
help of Transactions module.

4. Plain JDBC does not provide a callback interface feature.

Spring-JDBC is able to provide a callback interface feature.

5. Plain JDBC does not have mapper interfaces to map the data from ResultSet
object to Collection object.

Spring-JDBC module has direct mapper interfaces to map the data from
ResultSet object to Collection object.

6. In Plain JDBC, we are able to get the Connection object either through
DriverManager or through Connection Pooling, where to implement Connection
Pooling we have to write java code explicitly.

In Spring-JDBC, there is an inbuilt Connection pooling mechanism, where it is


not required to write java code for getting Connection pooling explicitly.

To perform Database operations in Spring-JDBC, SPring-JDBC module has


provided the complete predefined library in the form of
“org.springframework.jdbc” package which includes the following classes and
interfaces.

JdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcTemplate
SimpleJdbcCall
JdbcInsert
—---
—---

To prepare applications by using the Spring-JDBC module we have to use the


following steps.

1. Create Dao interface


2. Prepare Implementation class for DAO interface.
3. In the DAO implementation class, inject the JdbcTemplate object.
4. Perform Database operations by using JdbcTemplate methods.
5. Provide the following beans configuration in the Spring Configuration
file.
a. DataSource Configuration
b. JdbcTemplate with the dataSource property.
c. DAO Implementation class with the jdbcTemplate property.

6. Prepare Test class and access Dao methods in order to perform Database
operations.

JdbcTemplate:
—------------
JdbcTemplate is a class provided by Spring Framework, it has provided an
abstraction for the boilerplate code of the JDBC.

It has provided the following methods to write and execute sql queries.

1. For DDL Queries:


public void execute(String query)

2. For Non Select SQL queries:


public void update(String query)

3. For Select Sql queries:


public List queryForList(String sqlQuery, RowMapper mapper)
public Set queryForSet(String sqlQuery, RowMapper mapper)
public Map queryForMap(String sqlQuery, RowMapper mapper)
public Collection query(String sqlQuery, RowMapper mapper)
public Integer queryForInt(String sqlQuery)
public Float queryForFloat(String sqlQuery)
public Long queryForLong(String sqlQuery)
—---
EX:
EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);
public Employee search(int eno);
public List<Employee> getAllEmployees();
public String update(Employee employee);
public String delete(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

public JdbcTemplate getJdbcTemplate() {


return jdbcTemplate;
}

public String add(Employee employee) {


String status = "";
int rowCount = jdbcTemplate.update("insert into emp1
values
("+employee.getEno()+",'"+employee.getEname()+"',"+employee
.getEsal()+",'"+employee.getEaddr()+"')");
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {

List<Employee> empList= jdbcTemplate.query("select


* from emp1 where ENO = "+eno,(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> empList = jdbcTemplate.query("select
* from emp1", (rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME =
'"+employee.getEname()+"', ESAL = "+employee.getEsal()+",
EADDR = '"+employee.getEaddr()+"' where ENO =
"+employee.getEno();
int rowCount = jdbcTemplate.update(query);
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


String status = "";
int rowCount = jdbcTemplate.update("delete from emp1
where ENO = "+eno);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/contex
t"

xsi:schemaLocation="http://www.springframework.org/schema/b
eans

https://www.springframework.org/schema/beans/spring-beans.x
sd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-conte
xt.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDat
aSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="employeeDao"
class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
—-------
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEn
coding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>
In the case of JdbcTemplate, we are able to provide place holders or
positional parameters inside the sql queries in PreparedStatement
style, but we must provide values to the positional parameters
explicitly by using anonymous Object[] .

EX:
EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

public JdbcTemplate getJdbcTemplate() {


return jdbcTemplate;
}

public String add(Employee employee) {


String status = "";
String query = "insert into emp1 values (?,?,?,?)";

int rowCount = jdbcTemplate.update(query,new


Object[]{
employee.getEno(),
employee.getEname(),
employee.getEsal(),
employee.getEaddr()
});
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {

List<Employee> empList= jdbcTemplate.query("select


* from emp1 where ENO = ?",new Object[]{eno},(rs, rowNum)
-> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> empList = jdbcTemplate.query("select
* from emp1 where ESAL < ?",new Object[]{10000} ,(rs,
rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME = ?, ESAL = ?,
EADDR = ? where ENO = ?";

int rowCount = jdbcTemplate.update(query, new


Object[]{
employee.getEname(),
employee.getEsal(),
employee.getEaddr(),
employee.getEno()
});
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


String status = "";
int rowCount = jdbcTemplate.update("delete from emp1
where ENO = ?", new Object[]{eno});
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}
}

NamedParameterJdbcTemplate:
—----------------------------
In Spring JDBC, we are able to define names in place of place holders
in order to improve readability.

In SQL queries if we want to provide names to the parameters then we


have to use “NamedParameterJdbcTemplate”.

EX:
String query = “insert into emp1 values(:eno,:ename,
:esal,:eaddr)”;
To provide values to the named parameters we have to use the following
approaches.

1. By Using Map
2. By Using SqlParameterSource

1. By Using Map:
—----------------
In this approach, create a Map object and provide key-value pairs,
where keys must be the parameter names and values must be the
respective values.

EX:
String query = “insert into emp1 values(:eno,:ename,
:esal,:eaddr)”;
Map<String, Object> map = new HashMap<>();
map.put(“eno”, 111);
map.put(“ename”, “Durga”);
map.put(“esal”, 50000.0f);
map.put(“eaddr”, “Hyd”);

namedParameterJdbcTemplate.update(query, map);

1. In the Application, we have to use NamedParameterJdbcTemplate in


place of JdbcTemplate.
2. In the Spring COnfiguration File , inject DataSource to the
NamedParameterJdbcTemplate through Constructor Dependency
Injection.
3. IN DAO classes, provide namedParameters in place positional
parameters and assign values to the named parameters through a
Map object
EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);
public Employee search(int eno);

public List<Employee> getAllEmployees();

public String update(Employee employee);

public String delete(int eno);

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.namedparam.NamedParameterJdbc
Template;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDaoImpl implements EmployeeDao{


private NamedParameterJdbcTemplate
namedParameterJdbcTemplate;

public void
setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate
namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate =
namedParameterJdbcTemplate;
}

public NamedParameterJdbcTemplate
getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}

public String add(Employee employee) {


String status = "";
String query = "insert into emp1 values
(:eno,:ename,:esal,:eaddr)";
Map<String, Object> paramValues = new HashMap<>();
paramValues.put("eno", employee.getEno());
paramValues.put("ename", employee.getEname());
paramValues.put("esal", employee.getEsal());
paramValues.put("eaddr", employee.getEaddr());
int rowCount =
namedParameterJdbcTemplate.update(query,paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {

List<Employee> empList=
namedParameterJdbcTemplate.query("select * from emp1 where
ENO = :eno",Map.of("eno",eno),(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> empList =
namedParameterJdbcTemplate.query("select * from emp1 where
ESAL < :esal",Map.of("esal", 10000) ,(rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME = :ename, ESAL
= :esal, EADDR = :eaddr where ENO = :eno";

Map<String, Object> paramValues = new HashMap<>();


paramValues.put("eno", employee.getEno());
paramValues.put("ename", employee.getEname());
paramValues.put("esal", employee.getEsal());
paramValues.put("eaddr", employee.getEaddr());
int rowCount =
namedParameterJdbcTemplate.update(query, paramValues);
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


String status = "";
int rowCount =
namedParameterJdbcTemplate.update("delete from emp1 where
ENO = :eno", Map.of("eno", eno));
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/contex
t"

xsi:schemaLocation="http://www.springframework.org/schema/b
eans

https://www.springframework.org/schema/beans/spring-beans.x
sd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-conte
xt.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDat
aSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParame
terJdbcTemplate">
<constructor-arg name="dataSource"
ref="dataSource"/>
</bean>
<bean id="employeeDao"
class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="namedParameterJdbcTemplate"
ref="namedParameterJdbcTemplate"/>
</bean>

</beans>

App.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplication
Context;

import java.util.List;

public class App{


public static void main( String[] args ){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("AAA");
employee.setEsal(5000);
employee.setEaddr("Hyd");

String status = employeeDao.add(employee);


System.out.println("Status : "+status);

*/

/*
Employee employee = employeeDao.search(222);
if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
*/

/*
List<Employee> empList =
employeeDao.getAllEmployees();
if(empList == null){
System.out.println("No Employee is Existed");
}else{
for (Employee emp: empList ) {

System.out.print(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.
getEsal()+"\t"+emp.getEaddr()+"\n");
}
}

*/

/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);

*/

String status = employeeDao.delete(444);


System.out.println(status);
}
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEn
coding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>

By Using SqlparameterSource:
—---------------------------
Where SqlparameterSource is an interface, its implementation
classes are provided by the Spring Framework in the form of the
following classes.

1. MapSqlParameterSource
2. BeanPropertySqlparameterSource

MapSqlParameterSource:
—----------------------
If we want to provide values to the named parameters in sql
queries by using MapSqlparaeterSource then we have to use the
following method.

public MapSqlparameterSource addValue(String name, Object value)


EX:
String query = “insert into emp1 values(:eno, :ename, :esal,
:eaddr)”;
SqlParameterSource paramValues = new MapSqlparameterSource();
paramValues = paramValues.addValue(“eno”,111);
paramValues = paramValues.addValue(“ename”,”Durga”);
paramValues = paramValues.addValue(“esal”,5000);
paramValues = paramValues.addValue(“eaddr”,”Hyd”);
namedParameterJdbcTemplate.update(query, paramValues);

Ex:
EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);

public Employee search(int eno);

public List<Employee> getAllEmployees();

public String update(Employee employee);

public String delete(int eno);

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDaoImpl implements EmployeeDao{


private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate


namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {


return namedParameterJdbcTemplate;
}
public String add(Employee employee) {
String status = "";
String query = "insert into emp1 values (:eno,:ename,:esal,:eaddr)";
MapSqlParameterSource paramValues = new MapSqlParameterSource("eno",
employee.getEno());
paramValues = paramValues.addValue("ename", employee.getEname());
paramValues = paramValues.addValue("esal", employee.getEsal());
paramValues = paramValues.addValue("eaddr", employee.getEaddr());
int rowCount = namedParameterJdbcTemplate.update(query,paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {


MapSqlParameterSource paramValues = new MapSqlParameterSource("eno",
eno);
List<Employee> empList= namedParameterJdbcTemplate.query("select *
from emp1 where ENO = :eno",paramValues,(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
MapSqlParameterSource paramValues = new MapSqlParameterSource("esal",
10000);
List<Employee> empList = namedParameterJdbcTemplate.query("select * from
emp1 where ESAL < :esal",paramValues,(rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}
public String update(Employee employee) {
String status = "";
String query = "update emp1 set ENAME = :ename, ESAL = :esal, EADDR =
:eaddr where ENO = :eno";

MapSqlParameterSource paramValues = new MapSqlParameterSource();


paramValues.addValue("eno", employee.getEno());
paramValues.addValue("ename", employee.getEname());
paramValues.addValue("esal", employee.getEsal());
paramValues.addValue("eaddr", employee.getEaddr());
int rowCount = namedParameterJdbcTemplate.update(query, paramValues);
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


MapSqlParameterSource paramValues = new MapSqlParameterSource("eno",
eno);
String status = "";
int rowCount = namedParameterJdbcTemplate.update("delete from emp1 where
ENO = :eno", paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="namedParameterJdbcTemplate"
ref="namedParameterJdbcTemplate"/>
</bean>

</beans>

App.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class App{


public static void main( String[] args ){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("AAA");
employee.setEsal(5000);
employee.setEaddr("Hyd");

String status = employeeDao.add(employee);


System.out.println("Status : "+status);

*/

/*
Employee employee = employeeDao.search(222);
if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : "+employee.getEno());
System.out.println("Employee Name : "+employee.getEname());
System.out.println("Employee Salary : "+employee.getEsal());
System.out.println("Employee Address : "+employee.getEaddr());
}

*/

/*
List<Employee> empList = employeeDao.getAllEmployees();
if(empList == null){
System.out.println("No Employee is Existed");
}else{
for (Employee emp: empList ) {

System.out.print(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.getEsal()+"\t"+emp.
getEaddr()+"\n");
}
}

*/

/*

Employee employee = new Employee();


employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);

*/

String status = employeeDao.delete(444);


System.out.println(status);

}
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>
By using BeanPropertySqlParameterSource:
—----------------------------------------
In the case of NamedParameterJdbcTemplate , to provide values to the named
parameters if we use BeanPropertySqlParameterSource then we have to use the
following steps.

1. Create a Bean class with the named parameter names.


2. Create a Bean class object.
3. Create BeanpropertySqlParameterSource class object with the bean object
4. Pass BeanPropertySqlParameterSource object to update() method.

EX:
String query = “insert into emp1 values(:eno, :ename, :esal,
:eaddr)”;
Employee emp = new Employee();
emp.setEno(111);
emp.setEname(“Durga”);
emp.setEsal(5000);
emp.setEaddr(“Hyd”);
BeanPropertySqlParameterSource paramValues = new
BeanPropertySqlParameterSource(emp);
namedParameterJdbcTemplate.update(query, paramValues);

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);

public Employee search(int eno);

public List<Employee> getAllEmployees();

public String update(Employee employee);

public String delete(int eno);

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDaoImpl implements EmployeeDao{


private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate


namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {


return namedParameterJdbcTemplate;
}

public String add(Employee employee) {


String status = "";
String query = "insert into emp1 values (:eno,:ename,:esal,:eaddr)";
BeanPropertySqlParameterSource paramValues = new
BeanPropertySqlParameterSource(employee);
int rowCount = namedParameterJdbcTemplate.update(query,paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {


Employee emp1 = new Employee();
emp1.setEno(eno);
BeanPropertySqlParameterSource paramValues = new
BeanPropertySqlParameterSource(emp1);
List<Employee> empList= namedParameterJdbcTemplate.query("select *
from emp1 where ENO = :eno",paramValues,(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
Employee emp1 = new Employee();
emp1.setEsal(10000);
BeanPropertySqlParameterSource paramValues = new
BeanPropertySqlParameterSource(emp1);
List<Employee> empList = namedParameterJdbcTemplate.query("select * from
emp1 where ESAL < :esal",paramValues,(rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME = :ename, ESAL = :esal, EADDR =
:eaddr where ENO = :eno";

BeanPropertySqlParameterSource paramValues = new


BeanPropertySqlParameterSource(employee);
int rowCount = namedParameterJdbcTemplate.update(query, paramValues);
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


Employee emp = new Employee();
emp.setEno(eno);
BeanPropertySqlParameterSource paramValues = new
BeanPropertySqlParameterSource(emp);
String status = "";
int rowCount = namedParameterJdbcTemplate.update("delete from emp1 where
ENO = :eno", paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}
}

App.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class App{


public static void main( String[] args ){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("AAA");
employee.setEsal(5000);
employee.setEaddr("Hyd");

String status = employeeDao.add(employee);


System.out.println("Status : "+status);

*/

/*

Employee employee = employeeDao.search(222);


if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : "+employee.getEno());
System.out.println("Employee Name : "+employee.getEname());
System.out.println("Employee Salary : "+employee.getEsal());
System.out.println("Employee Address : "+employee.getEaddr());
}
*/
/*
List<Employee> empList = employeeDao.getAllEmployees();
if(empList == null){
System.out.println("No Employee is Existed");
}else{
for (Employee emp: empList ) {

System.out.print(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.getEsal()+"\t"+emp.
getEaddr()+"\n");
}
}

*/

/* Employee employee = new Employee();


employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);*/

String status = employeeDao.delete(444);


System.out.println(status);

}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="namedParameterJdbcTemplate"
ref="namedParameterJdbcTemplate"/>
</bean>

</beans>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>

SimpleJdbcTemplate:
—--------------------
Initially Spring 2.4 version was provided on the basis of JDk1.4 version,
When JDK1.5 version was introduced in Java a number of enhancements were
provided in JDK 1.5 version like Var-Arg method, Annotations,....

To provide JDk1.5 version features support in SpringFramework, Spring


Framework has provided SimpleJdbcTemplate class in its Spring2.5 version.

SimpleJdbctemplate class was managed by the Spring framework in its


Spring2.5, Spring 3.x, Spring 4.x, but it was removed from the Spring 5.x
version.

Dao Support Classes:


—--------------------
In Spring JDBC Applications, to get JdbcTemplate , NamedParameterJdbcTemplate
, SimpleJdbcTemplate in Dao classes we have to declare a property of type
XXXTemplate and its setter method.

In the above context, DAO Support classes are able to supply XXXTemplate
objects directly in DAO classes without declaring XXXTemplate property and
its setter method in the DAO classes.

Spring Framework has provided the following three types of DAO Support
classes.

1. JdbcDaoSupport
2. NamedParameterJdbcDaoSupport
3. SimpleJdbcDaoSupport

To get XXXTemplate classes, all the DAO Support classes are having the
following methods.

public JdbcTemplate getJdbcTemplate()


public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate()
public SimpleJdbcTemplate getSimpleJdbcTemplate()

EX:

public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao{


public String add(Employee employee){
getJdbcTemplate().update(“insert into emp1…………”);
}
}

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {
return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);

public Employee search(int eno);

public List<Employee> getAllEmployees();

public String update(Employee employee);

public String delete(int eno);

EmployeeDaoImpl.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTempl
ate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDaoImpl extends JdbcDaoSupport implements


EmployeeDao{

public String add(Employee employee) {


String status = "";
String query = "insert into emp1 values (?,?,?,?)";

int rowCount = getJdbcTemplate().update(query,new


Object[]{employee.getEno(), employee.getEname(),
employee.getEsal(), employee.getEaddr()});
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {

List<Employee> empList= getJdbcTemplate().query("select


* from emp1 where ENO = ?",new Object[]{eno},(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> empList = getJdbcTemplate().query("select
* from emp1 where ESAL < ?",new Object[]{10000} ,(rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME = ?, ESAL = ?,
EADDR = ? where ENO = ?";

int rowCount = getJdbcTemplate().update(query, new


Object[]{employee.getEname(), employee.getEsal(),
employee.getEaddr(), employee.getEno()});
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


String status = "";
int rowCount = getJdbcTemplate().update("delete from emp1
where ENO = ?", new Object[]{eno});
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

App.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;

import java.util.List;

public class App{


public static void main( String[] args ){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("AAA");
employee.setEsal(5000);
employee.setEaddr("Hyd");

String status = employeeDao.add(employee);


System.out.println("Status : "+status);

*/
/*
Employee employee = employeeDao.search(111);
if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}

*/
/*
List<Employee> empList = employeeDao.getAllEmployees();
if(empList == null){
System.out.println("No Employee is Existed");
}else{
for (Employee emp: empList ) {

System.out.print(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.getEs
al()+"\t"+emp.getEaddr()+"\n");
}
}*/

/*

Employee employee = new Employee();


employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);
*/

String status = employeeDao.delete(444);


System.out.println(status);

}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xs
d">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSour
ce">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name=”dataSource” ref=”dataSource”/>
</bean>
<bean id="employeeDao"
class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncodin
g>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>

NamedParameterJdbcDaoSupport:
—------------------------------
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

import java.util.List;

public interface EmployeeDao {


public String add(Employee employee);

public Employee search(int eno);

public List<Employee> getAllEmployees();

public String update(Employee employee);

public String delete(int eno);

}
EmployeeDaoImpl1.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import
org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSu
pport;
import
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTempl
ate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDaoImpl1 extends


NamedParameterJdbcDaoSupport implements EmployeeDao{

public String add(Employee employee) {


String status = "";
String query = "insert into emp1 values
(:eno,:ename,:esal,:eaddr)";
Map<String, Object> paramValues = new HashMap<>();
paramValues.put("eno", employee.getEno());
paramValues.put("ename", employee.getEname());
paramValues.put("esal", employee.getEsal());
paramValues.put("eaddr", employee.getEaddr());
int rowCount =
getNamedParameterJdbcTemplate().update(query,paramValues);
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}

public Employee search(int eno) {

List<Employee> empList=
getNamedParameterJdbcTemplate().query("select * from emp1 where
ENO = :eno",Map.of("eno",eno),(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList.isEmpty()?null:empList.get(0);
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> empList =
getNamedParameterJdbcTemplate().query("select * from emp1 where
ESAL < :esal",Map.of("esal", 10000) ,(rs, rowNum)->{
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return empList;
}

public String update(Employee employee) {


String status = "";
String query = "update emp1 set ENAME = :ename, ESAL =
:esal, EADDR = :eaddr where ENO = :eno";

Map<String, Object> paramValues = new HashMap<>();


paramValues.put("eno", employee.getEno());
paramValues.put("ename", employee.getEname());
paramValues.put("esal", employee.getEsal());
paramValues.put("eaddr", employee.getEaddr());
int rowCount =
getNamedParameterJdbcTemplate().update(query, paramValues);
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
return status;
}

public String delete(int eno) {


String status = "";
int rowCount =
getNamedParameterJdbcTemplate().update("delete from emp1 where
ENO = :eno", Map.of("eno", eno));
if(rowCount == 1){
status = "SUCCESS";
}else{
status = "FAILURE";
}
return status;
}
}

App.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;

import java.util.List;

public class App{


public static void main( String[] args ){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao1");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("AAA");
employee.setEsal(5000);
employee.setEaddr("Hyd");

String status = employeeDao.add(employee);


System.out.println("Status : "+status);

*/

/*
Employee employee = employeeDao.search(111);
if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
*/

/*
List<Employee> empList = employeeDao.getAllEmployees();
if(empList == null){
System.out.println("No Employee is Existed");
}else{
for (Employee emp: empList ) {

System.out.print(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.getEs
al()+"\t"+emp.getEaddr()+"\n");
}
}
*/
/*

Employee employee = new Employee();


employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);

*/

String status = employeeDao.delete(444);


System.out.println(status);

}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xs
d">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSour
ce">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJd
bcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<bean id="employeeDao1"
class="com.durgasoft.dao.EmployeeDaoImpl1">
<property name="dataSource" ref="dataSource"/>
</bean>

</beans>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>springjdbcapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springjdbcapp01</name>
<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncodin
g>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
</project>

SimpleDaoSupport class:
The main purpose of SImpleDaoSupport class is to supply
SimpleJdbcTemplate object to the DAO class without declaring
SimpleJdbcTemplate property in Dao implementation class.
This DaoSupport class did not exist in the Spring 5.0 version,
because SimpleJdbcTemplate was removed from the Spring 5.x
version.

Batch Updations:
—-----------------
IN general, in database applications,we will execute all the sql
queries by sending query by query from java application to the
database, where at database all the queries are executed one after
another and database Engine will send the results back to the java
application one after another.

The above approach will take a lot of transformation time to transfer


sql queries one by one , it will increase overall application
execution time, it will reduce application performance.

In database applications, to overcome the problem we need an


alternative that is “Batch Updations”.

In the case of Batch updates, we will gather all the sql queries as a
single batch , we will send batch of sql queries to the database at a
time , we will make the database Engine to execute batch of sql
queries and we will make the database engine to send all the results
at a time to the java applications.

In JDBC , batch updates are possible with Statement and with


PreparedStatement separately in different approaches.

In Spring Jdbc , batch updates are provided by Using the following


method from JdbcTemplate class.

public int[] batchUpdate(String queryInPreparedStatementStyle,


BatchPreparedStatementSetter setter)

Where BatchPreparedStatementSetter is an interface contains the


following methods.

1. public void setValues(PreparedStatement ps, int index)


2. public int getBatchSize()
Where setValues() method will be executed for each and every record to
set values to the placeholders provided in the sql query which is in
PreparedStatement.

Where getBatchSize() is able to return the number queries which are


there in the batch.

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public Employee(int eno, String ename, float esal, String eaddr) {


this.eno = eno;
this.ename = ename;
this.esal = esal;
this.eaddr = eaddr;
}

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}
public String getEaddr() {
return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.w3c.dom.stylesheets.LinkStyle;

import java.util.List;

public interface EmployeeDao {


public int[] insert(List<Employee> empList);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

@Override
public int[] insert(List<Employee> empList) {
int[] rowCounts = jdbcTemplate.batchUpdate("insert into emp1
values(?,?,?,?)", new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws
SQLException {
ps.setInt(1, empList.get(i).getEno());
ps.setString(2, empList.get(i).getEname());
ps.setFloat(3, empList.get(i).getEsal());
ps.setString(4, empList.get(i).getEaddr());
}

@Override
public int getBatchSize() {
return empList.size();
}
});
return rowCounts;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
List<Employee> empList = new ArrayList<>();

Employee emp1 = new Employee(111, "AAA", 5000, "Hyd");


Employee emp2 = new Employee(222, "BBB", 6000, "Hyd");
Employee emp3 = new Employee(333, "CCC", 7000, "Hyd");
Employee emp4 = new Employee(444, "DDD", 8000, "Hyd");
empList.add(emp1);
empList.add(emp2);
empList.add(emp3);
empList.add(emp4);

int[] rowCounts = employeeDao.insert(empList);


for(int rowCount: rowCounts){
System.out.println("RowCount : "+rowCount);
}

}
}
SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp02</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>

</project>

Stored procedures and Functions in Spring JDBC:


—-----------------------------------------------
Stored Procedure is a set of sql queries provided at databases and it
will perform a particular action when accessing it and it will not
return any value by using return statement.

create or replace procedure ProcName[(ParamList)]


AS
—Global Declarations—--
BEGIN
—----
—----
END procName;
/ —--> To save and compile procedure

Stored Function is a set of sql queries provided at databases and it


will perform a particular action when accessing it and it will return
value by using return statement.

create or replace function funName[(ParamList)] return DataType


AS
—Global Declarations—--
BEGIN
—----
—----
return value;
END funcName;
/ —--> To save and compile Function

In the above procedures and functions there are three types of


parameters.
1. IN type Parameter: It is able to get data from Procedure call
and it is able to provide data to the procedure body.
Syntax: varName IN DataType

2. OUT Type Parameter: It is able to get data from the Procedure


Body and it is able to send that data to the Procedure call.
Syntax: varName OUT DataType

3. INOUT Type parameter: These parameters are acting as IN type


Parameters and OUT type Parameters.

In Spring JDBC Applications, to access stored procedures and functions


Spring JDBC module has provided a predefined class in the form of
SimpleJdbcCall.

If we want to access Stored procedure and Function in Spring JDBC


applications then we have to use the following steps.

1. Define Stored procedure or Function at Database Side.


2. Prepare DAO interface and DAO implementation class.
3. Inside the DAO implementation class declare JDbcTemplate property
and its setter method.
4. In the DAO Implementation, create a SimpleJdbcCall object by
passing JdbcTemplate or DataSource as parameter.
5. Register Stored Procedure or Function name to the SimpleJdbcCall.
6. Execute Stored Procedure or function by passing the parameter
values.

EX:
EmployeeDao.java
package com.durgasoft.dao;

public interface EmployeeDao {


public double getEmployeeSalary(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import javax.sql.DataSource;
import java.util.Map;

public class EmployeeDaoImpl implements EmployeeDao{


private DataSource dataSource;

public void setDataSource(DataSource dataSource) {


this.dataSource = dataSource;
}

@Override
public double getEmployeeSalary(int eno) {
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource);
simpleJdbcCall.withProcedureName("getSal");
SqlParameterSource paramValue = new MapSqlParameterSource("no", eno);
Map<String, Object> result = simpleJdbcCall.execute(paramValue);

return (double)result.get("SAL");
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>
<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>

</beans>

Main.java
/*
create or replace procedure getSal(no IN int, sal OUT float)
AS
BEGIN
select ESAL into sal from emp1 where ENO = no;
END getSal;
/

*/
package com.durgasoft;

import com.durgasoft.dao.EmployeeDao;
import com.durgasoft.dao.EmployeeDaoImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
double sal = employeeDao.getEmployeeSalary(111);
System.out.println("Salary : "+sal);
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp04</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.0-XE</version>
</dependency>

</dependencies>
</project>

Using CURSOR Types in Procedures and Functions:


—------------------------------------------------
In Stored Procedures and Functions when we execute a select sql query
and when we get a set of records as a result then we have to represent
all the results in a single variable, here to store the result of a
particular select sql query there we have to use CURSORs .

All the databases are providing a set of predefined cursors to


represent the result of a particular sql query, where we will use
SYS_REFCURSOR in the applications.

To use CURSOR types in Stored Procedures we have to use the following


steps.

1. Declare SYS_REFCURSOR as an OUT Type parameter in the procedure


and function.
2. Open CURSOR type variable before executing select sql query.

To access Stored procedures and functions which are using CURSOR then
we have to use the following steps from Spring JDBC application.

1. Create a SimpleJdbcCall object with DataSource in dao.


2. Register Procedure name with SimpleJdbcCall.
3. Register the return type with Entity type.
EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}
EmployeeDao.java
package com.durgasoft.dao;

import java.util.Map;

public interface EmployeeDao {


public double getEmployeeSalary(int eno);
public Map<String, Object> getAllEmployees();
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import
org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

import javax.sql.DataSource;
import java.util.Map;

public class EmployeeDaoImpl implements EmployeeDao{


private DataSource dataSource;

public void setDataSource(DataSource dataSource) {


this.dataSource = dataSource;
}

@Override
public double getEmployeeSalary(int eno) {
SimpleJdbcCall simpleJdbcCall = new
SimpleJdbcCall(dataSource);
simpleJdbcCall.withProcedureName("getSal");
SqlParameterSource paramValue = new
MapSqlParameterSource("no", eno);
Map<String, Object> result =
simpleJdbcCall.execute(paramValue);

return (double)result.get("SAL");
}
@Override
public Map<String, Object> getAllEmployees() {
SimpleJdbcCall simpleJdbcCall = new
SimpleJdbcCall(dataSource);
simpleJdbcCall =
simpleJdbcCall.withProcedureName("getAllEmployees");
simpleJdbcCall = simpleJdbcCall.returningResultSet("emps",
BeanPropertyRowMapper.newInstance(Employee.class));
Map<String, Object> results = simpleJdbcCall.execute();
return results;
}
}

Main.java
/*
create or replace procedure getSal(no IN int, sal OUT float)
AS
BEGIN
select ESAL into sal from emp1 where ENO = no;
END getSal;
/

*/
/*
create or replace procedure getAllEmployees(emps OUT SYS_REFCURSOR)
AS
BEGIN
open emps for select * from emp1;
END getAllEmployees;
/
*/
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import com.durgasoft.dao.EmployeeDaoImpl;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.Map;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");

/* double sal = employeeDao.getEmployeeSalary(111);


System.out.println("Salary : "+sal);*/

Map<String, Object> results = employeeDao.getAllEmployees();


List<Employee> empList = (List<Employee>) results.get("emps");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
for(Employee employee: empList){
System.out.print(employee.getEno()+"\t");
System.out.print(employee.getEname()+"\t\t");
System.out.print(employee.getEsal()+"\t");
System.out.print(employee.getEaddr()+"\n");
}
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.OracleDriver"/>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>
<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp04</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.0-XE</version>
</dependency>

</dependencies>
</project>

BLOB And CLOB


—----------------
BLOB: Binary Large Objects: It is a data type in databases, it is able to
manage large volumes of binary data like images data,...

CLOB: Character large Objects: It is a data type in databases, it is able


to manage large volumes of character data like documents data,.....

In Spring JDBC, to process BLOB and CLOB data Spring JDBC has provided the
predefined library in the form of the following interfaces.

1. AbstractLobCreatingPreparedStatementCallback:
It can be used to Store BLOB data or CLOB data in the databases by
using the following method.

protected void setValues(PreparedStatement ps, LobCreator


lobCreator)throws SQLException

2. AbstractLobStreamingResultSetExtractor:
It can be used to retrieve BLOB and CLOB data from the databases.
protected abstract void streamData(ResultSet rs) throws
SQLException, IOException, DataAccessException;

3. LobCreator:
It has provided some methods to send data BLOB and CLOB to the database.

public void setBlobAsBinaryStream()


public void setClobAsCharacterStream()
4. LobHandler:
It has provided some methods to get BLOB data and CLOB data from the
database.

public void getBlobAsBinaryStream(---)


public void getClobAsCharacterStream(---)

EX:
Employee.java
package com.durgasoft.beans;

import java.io.File;

public class Employee {


private int eno;
private String ename;
private File emp_Image;
private File emp_Resume;

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 File getEmp_Image() {


return emp_Image;
}

public void setEmp_Image(File emp_Image) {


this.emp_Image = emp_Image;
}

public File getEmp_Resume() {


return emp_Resume;
}

public void setEmp_Resume(File emp_Resume) {


this.emp_Resume = emp_Resume;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

public interface EmployeeDao {


public void insertEmployee(Employee employee);
public Employee readEmployee(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStat
ementCallback;
import
org.springframework.jdbc.core.support.AbstractLobStreamingResultSetEx
tractor;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;
private LobHandler lobHandler;

public void setLobHandler(LobHandler lobHandler) {


this.lobHandler = lobHandler;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

@Override
public void insertEmployee(Employee employee) {
String query = "insert into emp10 values(?,?,?,?)";
jdbcTemplate.execute(query, new
AbstractLobCreatingPreparedStatementCallback(lobHandler) {
@Override
protected void setValues(PreparedStatement ps, LobCreator
lobCreator) throws SQLException, DataAccessException {
try {
ps.setInt(1, employee.getEno());
ps.setString(2, employee.getEname());
FileInputStream fileInputStream = new
FileInputStream(employee.getEmp_Image());
FileReader fileReader = new
FileReader(employee.getEmp_Resume());
lobCreator.setBlobAsBinaryStream(ps, 3,
fileInputStream, (int)employee.getEmp_Image().length());
lobCreator.setClobAsCharacterStream(ps, 4,
fileReader, (int)employee.getEmp_Resume().length());

}catch(IOException e){
e.printStackTrace();
}
}
});
}

@Override
public Employee readEmployee(int eno) {
Employee employee = new Employee();
String query = "select * from emp10 where ENO = "+eno;
jdbcTemplate.query(query, new
AbstractLobStreamingResultSetExtractor<Object>() {
@Override
protected void streamData(ResultSet rs) throws
SQLException, IOException, DataAccessException {
employee.setEno(rs.getInt("ENO"));
employee.setEname(rs.getString("ENAME"));

File image_File = new File("E:/spring/nagoor.jpg");


FileOutputStream fileOutputStream = new
FileOutputStream(image_File);

FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs,3),fileOutputS
tream);
employee.setEmp_Image(image_File);

File resume_File = new


File("E:/spring/nagoor_resume.docx");
FileWriter fileWriter = new FileWriter(resume_File);

FileCopyUtils.copy(lobHandler.getClobAsCharacterStream(rs, 4),
fileWriter);
employee.setEmp_Resume(resume_File);

}
});
return employee;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
/*
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("Durga");
employee.setEmp_Image(new File("E:\\images_new\\nag.jpg"));
employee.setEmp_Resume(new
File("E:\\documents\\nagoor.docx"));

employeeDao.insertEmployee(employee);
System.out.println("Employee Inserted Successfully");
*/
Employee employee = employeeDao.readEmployee(111);
System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Image :
"+employee.getEmp_Image().getAbsolutePath());
System.out.println("Employee Resume :
"+employee.getEmp_Resume().getAbsolutePath());
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.OracleDriver"/>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="lobHandler"
class="org.springframework.jdbc.support.lob.DefaultLobHandler"/>
<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
<property name="lobHandler" ref="lobHandler"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp05</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.0-XE</version>
</dependency>

</dependencies>
</project>

Connection pooling in Spring JDBC:


—----------------------------------
In general, in enterprise applications we have to interact with the
database and we have to perform database operations as per the
requirement.
In enterprise applications, to interact with the databases we have to
create a Connection object and we have to destroy connection object after
performing database operations.

In Enterprise applications, we may use more modules and more users wants
to access database, for every user and for every module creating a
separate connection object and destroying that connection objects will
consume more system memory and more execution time, it will affect the
enterprise application performance.

In the above situation, to improve enterprise application performance we


have to use “Connection pooling”.

In Connection pooling, we will create a set of Connection objects as


pool or as pools before starting application execution , we will
assign connection objects to the application on demand , when
Connection objects requirement is completed in the applications then
Application must send back that connection objects to the Pool objects
without destroying COnnection objects.

In The connection Pooling mechanisms , the application is not


responsible for creating connection objects and for destroying
connection objects, where providing connection objects and maintaining
Connection objects is the responsibility of Connection Pooling
mechanisms.

There are three approaches to provide connection pooling mechanisms .


1. Default Connection Pooling Mechanism
2. Third Party Connection Pooling mechanisms
3. Application Server provided Connection pooling Mechanism.

Default COnnection pooling Mechanism in Spring JDBC:


—----------------------------------------------------
IN Spring Jdbc module, there is an inbuilt connection pooling
mechanism which is existing in the form of DriverManagerDataSource.
If we want to use the inbuilt Connection Pooling Mechanism in Spring
JDBC applications then we have to provide DrivermanagerDataSource as a
bean in spring configuration file with the following properties.

driverClassName
url
username
password

EX:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>

Note: Default Connection pooling mechanism in Spring Framework is


suggestible for development purpose only, not suggestible for
Production mode.

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

public interface EmployeeDao {


public Employee search(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

@Override
public Employee search(int eno) {
List<Employee> empList = jdbcTemplate.query("select * from
emp1 where ENO = "+eno,(rs, rowNum)->{
Employee employee = new Employee();
employee.setEno(rs.getInt("ENO"));
employee.setEname(rs.getString("ENAME"));
employee.setEsal(rs.getFloat("ESAL"));
employee.setEaddr(rs.getString("EADDR"));
return employee;
});
return empList.isEmpty()?null: empList.get(0);
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">


<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
Employee employee = employeeDao.search(111);
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp06</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>

<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>

</dependencies>

</project>
Third party Provided Connection pooling mechanisms:
—---------------------------------------------------
Third party provided connection pooling mechanisms are more powerful
than Default Connection pooling mechanisms.

EX: Apache DBCP


C3P0
Proxool

Apache DBCP:
—------------
To use Apache DBCP Connection pooling mechanism we have to use the
following properties and Dependencies.

DataSource : BasicDataSource
driverClassName :
url
username:
password:
initialSize: initial number of connections in a pool
maxTotal: Allows max number of connections in a pool

Dependencies:
commons-dbcp2-version.jar
commons-pool2-version.jar

EX:
SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">


<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp06</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>

<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>

</dependencies>

</project>

Note: All the remaining components we have to get from Previous


example.

C3P0:
To use the C3P0 Connection pooling mechanism we have to use the
following properties and Dependencies.
DataSource : ComboPooledDataSource
driverClass :
jdbcUrl
user:
password:
minpoolsize: initial number of connections in a pool
maxpoolsize: Allows max number of connections in a pool

Dependencies:
c3p0-version.jar
machangecommons-java-version.jar

EX:
SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass"
value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="10"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">


<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp06</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>

<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.8</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.20</version>
</dependency>

</dependencies>

</project>

Proxool:
To use the Proxool Connection pooling mechanism we have to use the
following properties and Dependencies.

DataSource : ProxoolDataSource
driver:
driverUrl:
user:
password:
minimumconnectioncount: initial number of connections in a pool
maximumconnectioncount: Allows max number of connections in a pool

Dependencies:
proxool-version.jar
proxool-cglib.jar

EX:
SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource"
class="org.logicalcobwebs.proxool.ProxoolDataSource">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="driverUrl"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="minimumConnectionCount" value="5"/>
<property name="maximumConnectionCount" value="10"/>
</bean>
<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">


<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp06</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>

<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>com.cloudhopper.proxool</groupId>
<artifactId>proxool</artifactId>
<version>0.9.1</version>
</dependency>

</dependencies>

</project>

ApplicationServers Provided Connection pooling Mechanisms:


—---------------------------------------------------------
JNDI is “Java Naming And Directory Service”, it is able to provide
global scope to its resources in order to share those resources to all
the applications which are deployed in the present application server.

JNDI is an abstraction provided by J2EE and its implementations are


provided by almost all the application servers.

In SPring JDBC, we will use JNDI in the following way.


1. We will install Weblogic Server.
2. We must configure DataSource through JNDI in weblogic
3. We will run weblogic Server and activate JNDI
4. We must get a Datasource object from the Weblogic server provided
by JNDI.
5. We must use the generated DataSource in Spring-JDBC Application.

If we want to get the resources from the weblogic provided JNDI


server in Spring-Jdbc applications then we have to use the following
two actions.

1. Add the following jar files in buildpath.


C:\Oracle_Home\wlserver\server\lib\weblogic.war
C:\Oracle_Home\wlserver\server\lib\weblogic-spring.war

2. Provide DataSource configuration like below in the SPring


Configuration file.

<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="durga_jndi"/>
<property name="jndiEnvironment">
<props>
<prop
key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory
</prop>
<prop
key="java.naming.provider.url">t3://localhost:7001</prop>
</props>
</property>
</bean>
EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

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 float getEsal() {


return esal;
}
public void setEsal(float esal) {
this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}
EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

public interface EmployeeDao {


public Employee getEmployee(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao{


private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Override
public Employee getEmployee(int eno) {
List<Employee> empList = jdbcTemplate.query("select *
from emp1 where ENO = "+eno, (rs, rowNum)->{
Employee employee = new Employee();
employee.setEno(rs.getInt("ENO"));
employee.setEname(rs.getString("ENAME"));
employee.setEsal(rs.getFloat("ESAL"));
employee.setEaddr(rs.getString("EADDR"));

return employee;
});
return empList.isEmpty()?null:empList.get(0);
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicatio
nContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");
Employee employee = employeeDao.getEmployee(111);
if(employee == null){
System.out.println("Employee Does not Exist");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}

}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/
context"
xsi:schemaLocation="http://www.springframework.org/sc
hema/beans

https://www.springframework.org/schema/beans/spring-b
eans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring
-context.xsd">
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean
">
<property name="jndiName" value="durga_jndi"/>
<property name="jndiEnvironment">
<props>
<prop
key="java.naming.factory.initial">weblogic.jndi.WLIni
tialContextFactory</prop>
<prop
key="java.naming.provider.url">t3://localhost:7001</p
rop>
</props>
</property>
</bean>

<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="employeeDao"
class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="jdbcTemplate"
ref="jdbcTemplate"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springjdbcapp08</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>

<maven.compiler.source>8</maven.compiler.source>

<maven.compiler.target>8</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.so
urceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframewor
k/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.30.RELEASE</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframewor
k/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.30.RELEASE</version>
</dependency>

</dependencies>
</project>
==============================================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

</beans>

You might also like