Insert Single and Multiple Records Example using Spring JdbcTemplate

This tutorial will show you how you can insert an object or multiple objects into a database using Spring JdbcTemplate. So you are going to see how to insert single record and multiple records into database table. I am going to use PreparedStatement and BatchPreparedStatementSetter for inserting multiple records.

Sometimes you need to insert or update one or few records in the database. You can insert one or multiple records into database one by one in a traditional approach. Spring provides insert operation with the help of JdbcTemplate, it inserts or updates records into database in one shot.

Prerequisites

Java at least 8, Spring Boot 2.4.0, Gradle 6.5.1 or Maven 3.6.3

Project Setup

You can create either gradle or maven based project in your favorite IDE or tool. For gradle based project use the following build.gradle script:

buildscript {
	ext {
		springBootVersion = '2.4.0'
	}
	
    repositories {
    	maven {
    		url 'https://plugins.gradle.org/m2/'
    	}
    }
    
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter:${springBootVersion}")
	implementation("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}")
	
	implementation('mysql:mysql-connector-java:8.0.21')
	
	//required for JDK 9 or above
    implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359'
}

For maven based project you can use the following pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-jdbctemplate-insert-single-multiple-records</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.17</version>
		</dependency>
		
		<!--required only if jdk 9 or higher version is used-->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.4.0-b180830.0359</version>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

MySQL Table

I am creating one table student under roytuts database for testing single record insertion and multiple records insertion.

CREATE TABLE `student` (
  `student_id` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
  `student_name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `student_dob` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `student_email` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `student_address` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Datasource Configuration

I am creating an application.properties file under class path folder src/main/resources for declaring the database details.

#datasource
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/roytuts
jdbc.username=root
jdbc.password=root

Now I am creating the Java based configuration to create DataSource and JdbcTemplate.

package com.roytuts.spring.jdbctemplate.insert.single.multiple.records.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
public class DbConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getProperty("jdbc.url"));
        dataSource.setUsername(environment.getProperty("jdbc.username"));
        dataSource.setPassword(environment.getProperty("jdbc.password"));

        return dataSource;
    }

    @Bean
    public JdbcTemplate getJdbcTemplate() throws ClassNotFoundException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        return jdbcTemplate;
    }

}

Model

The following model class maps the database table student.

package com.roytuts.spring.jdbctemplate.insert.single.multiple.records.model;

import java.io.Serializable;

public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer studentId;
    private String studentName;
    private String studentDob;
    private String studentEmail;
    private String studentAddress;

    public Student() {
    }

    public Student(Integer studentId, String studentName, String studentDob, String studentEmail,
            String studentAddress) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentDob = studentDob;
        this.studentEmail = studentEmail;
        this.studentAddress = studentAddress;
    }

    // getters and setters

    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentDob=" + studentDob
                + ", studentEmail=" + studentEmail + ", studentAddress=" + studentAddress + "]";
    }

}

Mapper

To actually map table columns to Java fields in the Student class.

package com.roytuts.spring.jdbctemplate.insert.single.multiple.records.row.mapper;

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

import org.springframework.jdbc.core.RowMapper;

import com.roytuts.spring.jdbctemplate.insert.single.multiple.records.model.Student;

public class StudentDaoMapper implements RowMapper<Student> {

    @Override
    public Student mapRow(ResultSet rs, int arg1) throws SQLException {
        Student student = new Student();

        student.setStudentId(rs.getInt("student_id"));
        student.setStudentName(rs.getString("student_name"));
        student.setStudentDob(rs.getString("student_dob"));
        student.setStudentEmail(rs.getString("student_email"));
        student.setStudentAddress(rs.getString("student_address"));

        return student;
    }

}

Repository

This is not a Spring Data JPA repository but it’s a DAO layer code for interacting with database for performing the required operations for inserting records into the student table.

package com.roytuts.spring.jdbctemplate.insert.single.multiple.records.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.roytuts.spring.jdbctemplate.insert.single.multiple.records.model.Student;

@Repository
public class StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final String SQL_STUDENT_INSERT = "INSERT INTO student(student_name,student_dob,student_email,student_address) values(?,?,?,?)";

    public void insertSingleStudent(Student student) {
        Object[] studentParam = new Object[] { student.getStudentName(), student.getStudentDob(),
                student.getStudentEmail(), student.getStudentAddress() };

        jdbcTemplate.update(SQL_STUDENT_INSERT, studentParam);
    }

    public void insertMultipleStudents(List<Student> students) {
        jdbcTemplate.batchUpdate(SQL_STUDENT_INSERT, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement pStmt, int j) throws SQLException {
                Student student = students.get(j);
                pStmt.setString(1, student.getStudentName());
                pStmt.setString(2, student.getStudentDob());
                pStmt.setString(3, student.getStudentEmail());
                pStmt.setString(4, student.getStudentAddress());
            }

            @Override
            public int getBatchSize() {
                return students.size();
            }

        });
    }

}

Main Class

A class with main method and @SpringBootApplication is sufficient to start the application. I am running the application in CLI by implementing the interface CommandLineRunner.

package com.roytuts.spring.jdbctemplate.insert.single.multiple.records;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.roytuts.spring.jdbctemplate.insert.single.multiple.records.dao.StudentDao;
import com.roytuts.spring.jdbctemplate.insert.single.multiple.records.model.Student;

@SpringBootApplication
public class SpringInsertSingleMultipleRecordsApp implements CommandLineRunner {

    @Autowired
    private StudentDao studentDao;

    public static void main(String[] args) {
        SpringApplication.run(SpringInsertSingleMultipleRecordsApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        studentDao.insertSingleStudent(populateStudent());
        studentDao.insertMultipleStudents(populateStudents());
    }

    private Student populateStudent() {
        Student student = new Student();

        student.setStudentName("Sumit");
        student.setStudentDob("01-01-1980");
        student.setStudentEmail("sumit@email.com");
        student.setStudentAddress("Garifa");

        return student;
    }

    private List<Student> populateStudents() {
        List<Student> students = new ArrayList<Student>();

        Student student = new Student();
        student.setStudentName("Sumit");
        student.setStudentDob("01-01-1980");
        student.setStudentEmail("sumit@email.com");
        student.setStudentAddress("Garifa");

        students.add(student);

        student = new Student();
        student.setStudentName("Anjisnu");
        student.setStudentDob("01-01-1982");
        student.setStudentEmail("gourab@email.com");
        student.setStudentAddress("Garia");

        students.add(student);

        student = new Student();
        student.setStudentName("Debina");
        student.setStudentDob("01-01-1982");
        student.setStudentEmail("debina@email.com");
        student.setStudentAddress("Salt Lake");

        students.add(student);

        student = new Student();
        student.setStudentName("Souvik");
        student.setStudentDob("01-01-1992");
        student.setStudentEmail("souvik@email.com");
        student.setStudentAddress("Alipore");

        students.add(student);

        student = new Student();
        student.setStudentName("Liton");
        student.setStudentDob("01-01-1990");
        student.setStudentEmail("liton@email.com");
        student.setStudentAddress("Salt Lake");

        students.add(student);

        return students;
    }

}

Testing the Application

Running the above class will insert the single record as well as multiple records into the table. The table will have the following data:

spring jdbctemplate insert single and multiple records

That’s all about inserting single and multiple records into database table using Spring JdbcTemplate.

Source Code

Download

Leave a Comment