0% found this document useful (0 votes)
18 views21 pages

4 Day 4

The document discusses the use of stored procedures and functions in Spring JDBC, highlighting the differences between thick and thin client applications. It provides detailed explanations of how to create and access stored procedures and functions using SimpleJdbcCall, along with example code for implementing these concepts in a Java application. Additionally, it covers the use of cursor types for retrieving multiple records from stored procedures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views21 pages

4 Day 4

The document discusses the use of stored procedures and functions in Spring JDBC, highlighting the differences between thick and thin client applications. It provides detailed explanations of how to create and access stored procedures and functions using SimpleJdbcCall, along with example code for implementing these concepts in a Java application. Additionally, it covers the use of cursor types for retrieving multiple records from stored procedures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Java Frameworks Package

Stored Procedure and Functions in Spring JDBC:


Thik&Thin Client Application:
• Each Java Application/Program which interacts to the database act as client of the
RDBMS Package.

• On The basis of application architecture, application can be categorized in two


category

1) Thick client Application

2) Thin client Application.

The basic difference b/w a thick client & thin client application is of business logic.

Thick Client Model:

Thin Client Model:

2) In thin client application business logic is implemented as part of the RDBMS package

Advantage of thin client model is performance better than thick and disadvantage is, it is
database dependent.

1 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

What Is a Stored Procedure?

A procedure is a type of subprogram that performs an action.

A procedure can be stored in the database, as a schema object, for repeated execution.

What is a Function:

• A function is a named PL/SQL block that returns


a value.

• A function can be stored in the database as a schema object for repeated execution.

• A function is called as part of an expression.

Comparing Procedures and Functions:

2 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

The Major difference b/w Procedure and Function is of mode of returning values.

The Function returns a value explicitly or directly where as Procedure only returns a
value indirectly.

In general, in Database related applications which database logic


we want to execute frequently that database logic we are going
to manage at Database side and we will access that database
logic from Client application whenever we require, for this we
have to use Stored Procedures and Functions.

Q)What is the difference between Stored Procedure and Function?


—-----------------------------------------------------------------------------
Ans:
—---
Stored procedure is a set of instructions representing a particular
action at the database, it will not use a return statement to return
a value.

Stored function is a set of instructions representing a particular


action at the database, it will use a return statement to return a
value.

Syntax: Procedure
create or replace procedure ProcName[(ParamList)]
AS
—---Global Variables—---
BEGIN
—--Database Logic—-----
3 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

End ProcName;
/ —-> To save procedure at Database

Syntax: Function
Create or replace Function functionName[(ParamValues)] as
ReturnType
—--Global Variables—--
BEGIN
—----Database Logic—----
Return value;
END functionName;
/→ To save Function.

If we want to access Stored procedures and Functions in Jdbc


applications we have to use CallableStatement.

In Spring Jdbc , to access stored procedures and functions we


have to use SimpleJdbcCall.

If we want to access stored procedures and functions which are available at database from
Spring Jdbc application then we have to use "SimpleJdbcCall".

To use SimpleJdbcCall in Spring Jdbc applications we have to use the following steps.

1) Create DAO interface and its implementation class.


2) IN DAO implementation class, we have to declare DataSource and JdbcTemplate and
its respective setter method .
3) In side setter method we have to create SimpleJdbcCall object.

SimpleJdbcCall jdbcCall = new SimpleJdbcCall();


jdbcCall.withProcedureName("proc_Name");

4) Configure DataSource and DAO implementation class in beans configuration file.


5) Access "execute" method by passing IN type parameters values in the form of
"SQLParameterSource".

public Map execute(Map m)


pubhlic Map execute(SqlParameterSource paramSource)
public Map execute(Object ... obj)

Procedure to copy at Database:

4 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

create or replace procedure getSalary(no IN number, sal OUT int)


AS
BEGIN
select esal into sal from employee where eno = no;
END getSalary;
/

Project Name [App05]

Update the pom.xml with dependencies.

<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-
core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-
context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-
jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.23</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc
11 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>21.7.0.0</version>
</dependency>

5 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

</dependencies>

Create some packages like [beans and dao]

[Employee.java]

package com.ccteam.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;
6 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
}
}

[EmployeeDao.java]

package com.ccteam.dao;
import com.ccteam.beans.Employee;
public interface EmployeeDao
{
public void create(Employee emp);
public Object getEmployeeSalary(int eno);
}

[EmployeeDaoImpl.java]
package com.ccteam.dao;

import com.ccteam.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
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;
private SimpleJdbcCall jdbcCall;
public void setDataSource(DataSource dataSource)
{
this.dataSource = dataSource;
jdbcCall = new
SimpleJdbcCall(dataSource).withProcedureName("getSalary");
}
@Override
public void create(Employee emp) {
try {
JdbcTemplate jdbcTemplate = new
JdbcTemplate(dataSource);
String sql= "insert into employee
values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()

7 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
+" ,'"+emp.getEaddr()+"')";
jdbcTemplate.update(sql);
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public Object getEmployeeSalary(int eno)
{
SqlParameterSource in = new
MapSqlParameterSource().addValue("no", eno);
Map<String, Object> map = jdbcCall.execute(in);
// System.out.println(map);
return map.get("SAL");
}

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

xmlns: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 = "oracle"/>
</bean>

8 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
<bean id="empDao" class="com.ccteam.dao.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>

</beans>

[Main.java]
package com.ccteam;

import com.ccteam.beans.Employee;
import com.ccteam.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContex
t;

public class Main


{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
Employee emp1 = new Employee();
emp1.setEno(111);
emp1.setEname("AAA");
emp1.setEsal(5000);
emp1.setEaddr("Agra");
dao.create(emp1);
Object salary1 = dao.getEmployeeSalary(emp1.getEno());
System.out.println(emp1.getEno()+"---->"+salary1);
Employee emp2 = new Employee();
emp2.setEno(222);
emp2.setEname("BBB");
emp2.setEsal(6000);
emp2.setEaddr("Mathura");
dao.create(emp2);
Object salary2 = dao.getEmployeeSalary(emp2.getEno());
System.out.println(emp2.getEno()+"---->"+salary2);

}
}

9 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

And Run the Application.

Using CURSOR Types in Procedures:

Here we return only one value, it may be float or double , but, my


requirement is that we want records of data[ResultSet] from
Stored procedure and function.

If we want to return records of data from Stored procedure or


from store functions then we have to use CURSOR types.

If we want to use CURSOR types in Stored Procedures in order to retrieve


multiple Records data then we have to use the following method on
SimpleJdbcCall reference.

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource)

jdbcCall = jdbcCall.withProcedureName("getAllEmployees");
jdbcCall = jdbcCall.returningResultSet("emps",BeanPropertyRowMapper.newInstance(Employee.class));

After adding returningResultSet(--,--) method, if we access execute() method on


SimpleJdbcCall then execute() method will execute procedure, it will get all the
results from CURSOR type variable and stored all records in the form of
Employee objects in an ArrayList object with "emps"[CURSOR TYPE variable] key
in a Map.

Example:
[COPY this Procedure in Database ]

create or replace procedure getAllEmployees(emps OUT SYS_REFCURSOR)


AS

10 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
BEGIN
open emps for
select * from employee;
END getAllEmployees;
/

[Employee.java]

package com.ccteam.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()

11 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

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;

12 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

[EmployeeDao.java]

package com.ccteam.dao;

import java.util.Map;

public interface EmployeeDao

public Map<String, Object> getAllEmployees();

[EmployeeDaoImpl.java]
public class EmployeeDaoImpl implements EmployeeDao

private SimpleJdbcCall jdbcCall;

private DataSource dataSource;

public void setDataSource(DataSource dataSource)

this.dataSource = dataSource;

jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getAllEmployees");

jdbcCall = jdbcCall.returningResultSet("emps",

BeanPropertyRowMapper.newInstance(Employee.class));

@Override

13 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

public Map<String, Object> getAllEmployees()

Map<String, Object> map = jdbcCall.execute();

//System.out.println(map);

return map;

[applicationContext.xml]

<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 = "oracle"/>

</bean>

<bean id="empDao" class="com.ccteam.dao.EmployeeDaoImpl">

<property name="dataSource" ref="dataSource"/>

</bean>

[Main.java]

Type this within main method

public static void main(String[] args)throws Exception

14 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

ApplicationContext context = new


ClassPathXmlApplicationContext("applicationContext.xml");

EmployeeDao dao = (EmployeeDao)context.getBean("empDao");

Map<String, Object> map = dao.getAllEmployees();

System.out.println(map);

ArrayList<Employee> list =(ArrayList<Employee>) map.get("emps");

System.out.println(list);

System.out.println("Employee Details");

System.out.println("ENO\tENAME\tESAL\tEADDR");

System.out.println("-----------------------------");

for(Employee e: list)

System.out.println(e.getEno()+"\t"+e.getEname()+"\t"+e.getEsal()+"\t"+e.getEaddr());

And Run the Application.

Calling Stored Function

Following example will demonstrate how to call a stored function using Spring JDBC. We'll read
one of the available records in Student Table by calling a stored function. We'll pass an id and
receive a student name.

15 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

Syntax
SimpleJdbcCall jdbcCall = new
SimpleJdbcCall(dataSource).withFunctionName("get_student_name");

SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);


String name = jdbcCall.executeFunction(String.class, in);

Student student = new Student();


student.setId(id);
student.setName(name);

Where,
 in − SqlParameterSource object to pass a parameter to a stored function.
 jdbcCall − SimpleJdbcCall object to represent a stored function.

 student − Student object.

Create the following Stored function in MySQl Database:

DELIMITER //

CREATE FUNCTION `get_student_name` (in_id VARCHAR(10))

RETURNS varchar(200) DETERMINISTIC

BEGIN

DECLARE out_name VARCHAR(200);

SELECT SName

INTO out_name

FROM Student where SId = in_id;

16 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

RETURN out_name;

END

//
DELIMITER ;

What is the meaning of deterministic in MySQL function?


A deterministic function always returns the same results if given the same input
values. A nondeterministic function may return different results every time it is called,
even when the same input values are provided.

Project Name [App06]

Update the pom file with dependencies.

[Student.java]

package com.ccteam.beans;
public class Student {

private String name;


private String id;
private String address;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public String getAddress() {


return address;
}

17 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package

public void setAddress(String address) {


this.address = address;
}
}
[StudentDao.java]
package com.ccteam.dao;

import com.ccteam.beans.Student;

import javax.sql.DataSource;

public interface StudentDao


{
public void setDataSource(DataSource ds);
public Student getStudent(String id);
}

[StudentMapper.java]
package com.ccteam.dao;

import com.ccteam.beans.Student;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentMapper implements RowMapper<Student>


{
public Student mapRow(ResultSet rs, int rowNum) throws
SQLException {
Student student = new Student();
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setAddress(rs.getString("address"));
return student;
}
}

[StudentDaoImpl.java]

18 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
package com.ccteam.dao;

import com.ccteam.beans.Student;
import org.springframework.jdbc.core.JdbcTemplate;
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;

public class StudentDaoImpl implements StudentDao


{
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;

public void setDataSource(DataSource dataSource)


{
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public Student getStudent(String id)
{
SimpleJdbcCall jdbcCall = new
SimpleJdbcCall(dataSource).withFunctionName("get_student_name");
SqlParameterSource in = new
MapSqlParameterSource().addValue("in_id", id);
String name = jdbcCall.executeFunction(String.class, in);
String address = jdbcCall.executeFunction(String.class,
in);

Student student = new Student();


student.setId(id);
student.setName(name);
student.setAddress(address);
return student;
}
}
[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

19 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd ">

<!-- Initialization for data source -->


<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:3306/College"/>
<property name = "username" value = "root"/>
<property name = "password" value = "mysql"/>
</bean>

<!-- Definition for studentJDBCTemplate bean -->


<bean id = "student"
class = "com.ccteam.dao.StudentDaoImpl">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>

[Main.java]
package com.ccteam;

import com.ccteam.beans.Student;
import com.ccteam.dao.StudentDaoImpl;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContex
t;

public class Main {


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

StudentDaoImpl studentDaoImpl =
(StudentDaoImpl)context.getBean("student");

Student student = studentDaoImpl.getStudent("S-111");


System.out.print("ID : " + student.getId() );

20 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)
Java Frameworks Package
System.out.print(", Name : " + student.getName() );
System.out.print(", Address : " + student.getAddress() );
}
}

And Run the Application.

21 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses


C,DSA,Java,Python,Web Develoment ETC… Visit www.careercompiler.com
Prepared By DD Singh,Coding Career Expert(17 Years Experience)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy