Languages
[Edit]
EN

Spring Boot 2 - JdbcTemplate INSERT query example to MySQL database

3 points
Created by:
Creg
9600

In this article, we would like to show how to execute INSERT query to MySQL database in Spring Boot 2 application that uses JdbcTemplate API.

Final result:

Spring Boot 2 + JdbcTemplate - example JSON result.
Spring Boot 2 + JdbcTemplate - example JSON result.

Project structure: 

Spring Boot 2 + JdbcTemplate - example project structure.
Spring Boot 2 + JdbcTemplate - example project structure.

DemoApplication.java file:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

 

UsersController.java file:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;
import java.util.List;

@Controller
public class UsersController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // POST http://localhost:8080/api/user/create
    // echo '{"name":"john","email":"john@email.com"}' | curl -X POST -H "Content-Type: application/json" -d @- http://localhost:8080/api/user/create
    //
    @PostMapping(
            value = "/api/user/create",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    @ResponseBody
    public UserEntity createUser(@RequestBody UserEntity userEntity) throws SQLException {
        long userId = this.insertUser(userEntity);
        return this.fetchUser(userId);
    }

    private long insertUser(UserEntity userEntity) throws SQLException {
        String query = "INSERT INTO `users`\n" +
                       "\t(`name`, `email`)\n" +
                       "VALUES\n" +
                       "\t(?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator statementCreator = (Connection connection) -> {
            PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1, userEntity.getName());
            preparedStatement.setString(2, userEntity.getEmail());
            return preparedStatement;
        };
        int updatesCount = this.jdbcTemplate.update(statementCreator, keyHolder);
        if (updatesCount == 1) {
            Number generatedKey = keyHolder.getKey();
            if (generatedKey == null) {
                throw new SQLException("Getting user id error.");
            }
            return generatedKey.longValue();
        }
        throw new SQLException("Expected one row insert."); // should never happen
    }

    private UserEntity fetchUser(long userId) {
        String query = "SELECT `id`, `name`, `email`\n" +
                       "FROM `users`\n" +
                       "WHERE `id` = ?\n" +
                       "LIMIT 1";
        PreparedStatementCreator statementCreator = (Connection connection) -> {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setLong(1, userId);
            return preparedStatement;
        };
        List<UserEntity> users = this.jdbcTemplate.query(statementCreator, new UserRowMapper());
        if (users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }

    private class UserRowMapper implements RowMapper<UserEntity> {
        @Override
        public UserEntity mapRow(ResultSet resultSet, int rowNumber) throws SQLException {
            UserEntity user = new UserEntity();
            user.setId(resultSet.getLong("id"));
            user.setName(resultSet.getString("name"));
            user.setEmail(resultSet.getString("email"));
            return user;
        }
    }
}

 

UserEntity.java file:

package com.example.demo;

public class UserEntity {

    private long id;
    private String name;
    private String email;

    public UserEntity() { }

    public UserEntity(long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

 

application.properties file:

db.host=localhost
db.port=3306
db.name=example_db

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://${db.host}:${db.port}/${db.name}?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=UTC&character_set_server=utf8mb4
spring.datasource.username=root
spring.datasource.password=root

 

pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</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.22</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

Database preparation

CREATE DATABASE `example_db`


CREATE TABLE `users` (
	`id` BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`email` VARCHAR(255) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

 

Related snippets

  1. Spring Boot 2 - JdbcTemplate INSERT query example to MySQL database (only insert)

  2. Spring Boot 2 - JdbcTemplate INSERT query example to MySQL database (insert + fetch)

See also

  1. Spring Boot 2 - JdbcTemplate SELECT query example to MySQL database
  2. Java - how to make MySQL insert query with JDBC?

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join