Execute Stored Procedure in Spring Jdbc

By Dhiraj Ray, 04 February,2017   2033

Spring jdbc provides very simple approach to execute stored procedures using SimpleJdbcCall.In this post we will be dicussing about how to execute stored proc in spring spring jdbc using SimpleJdbcCall.

Server Side

Follwing is a sample user class which will be persisted in the DB by calling a stored proc.

package com.devglan.model; public class User { private int id; private String name; private String address; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

Following is the class having an implementation to execute stored proc.Following method createUser() takes user object as a parameter and executes the stored proc create_user.

package com.devglan.dao.impl; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.stereotype.Repository; import com.devglan.dao.UserDao; import com.devglan.model.User; @Repository public class UserDaoImpl implements UserDao { private SimpleJdbcCall createUserProc; @Autowired public void setDataSource(DataSource dataSource) { this.createUserProc = new SimpleJdbcCall(dataSource).withProcedureName("create_user").withReturnValue(); } @Override public User createUser(User user){ String userId = null; SqlParameterSource inParams = new MapSqlParameterSource() .addValue("name", user.getName()) .addValue("email", user.getEmail()) .addValue("address", user.getAddress()); Map result = createUserProc.execute(inParams); userId = (String) result.get("id"); user.setId(userId); return user; } }


I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Further Reading on Spring Jdbc

1. Insert Record In Db With Spring Boot Jdbctemplate

2. Insert Record In Db With Spring Boot Namedparameter Jdbctemplate

3. Fetch Auto Generated Primary Key Value After Insert Spring Jdbc

4. Working With Springboot Jdbctemplate

5. Working With Springboot Namedparameter Jdbctemplate

Suggest more topics in suggestion section or write your own article and share with your colleagues.