Tag Archives: Stored Procedures

Using JdbcTemplate in Spring Boot to Insert a Record and Return a ID

There is more than one way to skin a cat (pardon to my cats). In fact, to insert a record into a database within Spring Boot, I found at least 6 ways:

  • StoredProcedureQuery
  • Prepared Statements (with various flavors)
  • Callable Statements (with various flavors)
  • JdbcTemplates
  • JdbcTemplates with Prepared Statements
  • JdbcTemplates with Callable Statements

There were probably more. But I didn’t save my search history to find them all again.

I have an unique situation in which I’m working. The database on the backend is Microsoft SQL Server. The insert statement is using a Stored Procedure. And the stored procedure is returning the record id by calling @@IDENTITY itself.

Oftentimes, when one is working with MSSQL, one is working with the entire Microsoft stack, which includes some flavor of .Net. But the client wanted to have all their middleware code standardized to Spring Boot. Not a big deal, except for the fact that there were existing Stored Procedures to work with, not the database tables directly.

This has provided a few unique challenges. Rather than using Spring Boot’s ready-made method for automatically creating models for databases, the models had to be created by hand. And I learned early on that, when using StoredProcedureQuery, ‘column names’ wouldn’t work: the parameters had to be entered in the order expected by the stored procedure, and indices used instead.

That last item took a day to figure out.This latest issue took just about as long. And hopefully, some poor soul will find this post to aid in their quest for the same information.

That problem was inserting a record and returning the new id for that record. The first problem was dealing with null values. StoredProcedureQuery had been infinitely useful when running stored procedures that extracted data. It became almost cookie cutter to create the code:

StoredProcedureQuery query = [EntityManager].createStoredProcedureQuery("[stored procedure name]", [Model class].class);
query.registerStoredProcedureParameter([index], [typeclass].class, ParameterMode.IN [or] ParameterMode.OUT);
return query.getSingleResult(); [or] return query.getResultList();

But this wouldn’t work for inserts. Initially, my problem with inserts was that they could contain null values. StoredProcedureQuery didn’t like null values. And, after much research and trial and error, I found that JdbcTemplate was my friend. By using JdbcTemplate, I could add null parameters and the code wouldn’t choke on me. Problem was, JdbcTemplate.update, which I was using, would return the number of records affected, but not the new ID, if a record was being inserted. Thus began my long search for something else that would work.

The popular response in Stack Overflow was to use:

KeyHolder holder = new GeneratedKeyHolder();

I couldn’t make that work. I’d get errors because ‘nothing’ was being returned.

I checked all the other options on JdbcTemplate, since that still seemed my best option for accomplishing this (since I might have nulls in the insert parameters). I literally would check the documentation for each option, then Google to see how they were used.

I finally came across the documentation for CallableStatement. It is passed as a parameter in a call from JdbcTemplate, so my null values could be handled. And it allowed a return value to be ‘registered’ for retrieval. That is, since I was not retrieving a value with a column or variable name, I could set one in order to find the value after the call had been made.

My thanks to these two sources to helping me out:


Here’s the basic syntax that I ended up using:

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java util.Map;

import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;

// note: I did have to list all my input and output parameter types, unlike in
// the examples where the list only included the output type
List out = new ArrayList();
out.add(new SqlParameter(1, Types.NVARCHAR));
out.add(new SqlParameter(2, Types.INTEGER));
out.add(new SqlOutParameter(“id”,Types.NUMERIC));

Map<String, Object> returnList
= getJdbcTemplate().call(new MyCallableStatementCreator(params), out);


class MyCallableStatementCreator implements CallableStatementCreator {

private ParamModel params;

public MyCallableStatementCreator(ParamModel param) {
this.params = params;
public CallableStatement createCallableStatement(Connection con) throws SQLException {
// note: I received an error until I put the brackets around the call, and the word ‘call’ was required
CallableStatement stmt = con.prepareCall(“{call my_stored_procedure(?,?,?) }”);

stmt.setInt(2, params.getSecondVal());
stmt.registerOutParameter(3, Types.INTEGER);
return stmt;