

How to call Stored Procedures from Java using IN and OUT parameter - Spring Fram...
source link: https://javarevisited.blogspot.com/2013/04/spring-framework-tutorial-call-stored-procedures-from-java.html#axzz8AnF375To
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to call Stored Procedures from Java using IN and OUT parameter - Spring Framework Example Tutorial

In order to demonstrate, how to call stored procedures from the spring-based application, we will first create a simple stored proc using MySQL database, as shown below.
It' also the most up-to-date and covers Spring 5. It's also very affordable and you can buy in just $10 on Udemy sales which happen every now and then.
MySQL Stored procedure
mysql> DELIMITER // mysql> create procedure usp_GetEmployeeName(IN id INT, OUT name VARCHAR(20)) -> begin -> select emp_name into name from employee where emp_id = id; -> end// Query OK, 0 rows affected (0.52 sec) mysql> DELIMITER ;
mysql> call usp_GetEmployeeName(103, @name); Query OK, 1 row affected (0.05 sec) mysql> select @name; +-------+ | @name | +-------+ | Jack | +-------+ 1 row in set (0.00 sec)
Spring Stored Procedure example and Configurations
If you look at the constructor of EmployeeSP, it calls super class constructor and passes data source and name of database stored procedure. We have also declared two stored procedure parameters, one is IN parameter id, and the other is the OUT parameter.
Input to the stored the procedure is passed using the IN parameter, and output from the stored procedure is read using the OUT parameter.
Your stored procedure can have multiple IN and OUT parameters. StoredProcedure class also provides several execute() methods, which can be invoked to call a stored procedure and get a result. It returns the result as Map, where the key is OUT parameter, and value is the result of a stored procedure.
Here is the code for DAO class and stored procedure along with the Spring Configuration file, since the Spring framework is based on the principle of Dependency Injection and Inversion of control, this file is required to create and manage objects.
Java Class which wraps Stored procedure
import java.sql.Types; import java.util.Map; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.object.StoredProcedure; public class EmployeeDao { private JdbcTemplate jdbcTemplate; private EmployeeSP sproc; public void setDataSource(DataSource source){ this.jdbcTemplate = new JdbcTemplate(source); this.sproc = new EmployeeSP(jdbcTemplate.getDataSource()); } /* * wraps stored procedure call */ public String getEmployeeName(int emp_id){ return (String) sproc.execute(emp_id); } /* * Inner class to implement stored procedure in spring. */ private class EmployeeSP extends StoredProcedure{ private static final String SPROC_NAME = "usp_GetEmployeeName"; public EmployeeSP( DataSource datasource ){ super( datasource, SPROC_NAME ); declareParameter( new SqlParameter( "id", Types.INTEGER) ); //declaring sql in parameter to pass input declareParameter( new SqlOutParameter( "name", Types.VARCHAR ) ); //declaring sql out parameter compile(); } public Object execute(int emp_id){ Map<String,Object> results = super.execute(emp_id); return results.get("name"); //reading output of stored procedure using out parameters } } }
Main class to test stored procedure
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * Main class to start and test this Java application */ public class Main { public static void main(String args[]){ ApplicationContext ctx = new ClassPathXmlApplicationContext ("spring-config.xml"); EmployeeDao dao = (EmployeeDao) ctx.getBean("employeeDao"); //calling stored procedure using DAO method System.out.println("Employee name for id 103 is : " + dao.getEmployeeName(103)); } } Output 2013-01-17 23:56:34,408 0 [main] DEBUG EmployeeDao$EmployeeSP - Compiled stored procedure. Call string is [{call usp_GetEmployeeName(?, ?)}] 2013-01-17 23:56:34,439 31 [main] DEBUG EmployeeDao$EmployeeSP - RdbmsOperation with SQL [usp_GetEmployeeName] compiled Employee name for id 103 is : Jack
Spring configuration file:
.PropertyPlaceholderConfigurer">
.SingleConnectionDataSource">
Spring Framework 5: Beginner to Guru
- Top 5 Spring Boot Features Java developer should know (features)
- How to setup LDAP authentication in Java using Spring Security? (solution)
- Top 5 Courses to learn Spring in depth (courses)
- 10 Free Courses to learn Spring Boot for Beginners (free courses)
- 21+ Spring MVC Interview Questions for Java developers (Questions)
- Top 5 Courses to learn Microservices in Java (courses)
- How to Crack Spring Certification for Java developers (certification)
- 10 Advanced Spring Boot Courses for Java developers (courses)
- How to get a ServletContext object in the Spring controller? (example)
- Top 5 Courses to learn Spring Boot in-depth (courses)
- 10 example of display tag in JSP and spring (examples)
- Top 5 Books to learn Spring Boot and Spring Cloud (books)
- What is the default bean scope in the Spring MVC framework? (answer)
- Top 5 Courses to learn Spring Cloud for Java developers (courses)
6 comments :
Liberty Bell said...
Thanks for this tutorial. It's brilliant.
Unfortunately if I try this I get the following error
java.sql.SQLException: boo!
springframework.dao.TransientDataAccessResourceException: CallableStatementCallback; SQL [{call sp_MyStoredProc(?, ?, ?)}]; boo!
I am using org.springframework.jdbc-3.1.3 and
mysql-connector-java-5.1.25
Javin @ programming puzzles said...
@Liberty Bell, do you have this stored procedure and table created in database? TransientDataAccessResourceException comes when resource is temporarily unavailable, could be table or stored proc. I would suggest retrying after running stored procedure in database itself, just to make sure it's working.
Prafful said...
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`name`)' at line 1
I am using MySQL-5.6.14 version.
Anonymous said...
Thanks for your tutorial, It's working perfectly in my project.
But I have a little problem, the stored procedured that it's calling since my dao class modifiy several tables and it's probably that finishes with error. In this case the java program must to do a rollback to get back the data in initial values.
How can I do that?
I tried to add the annotation @Transactional(rollbackFor=Exception.class) in the execute method, but it doesn't work.
Thanks for advance.
Regrads.
Jose Pascual Gimeno
Anonymous said...
can you please upload the project as well, it will be helpful for beginners
Govil Kumar G said...
Hi All,
Please share a example or let me know how to pass sysrefcursor as an input parameter to oracle procedure from java using SimpleJdbcCall and SqlParameter
Thanks in advance
Post a Comment
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK