Execute Stored Procedure in Spring Jdbc

By Dhiraj Ray, 04 February,2017  

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.

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

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: