Insert Record in DB with SpringBoot JdbcTemplate

By Dhiraj Ray, 04 February,2017   1461

In this post you will learn how to insert record in database with spring boot jdbctemplate.With the artifact spring-boot-starter-jdbc provided by spring boot, it has become even more convenient to configure spring jdbc related configurations.It does not require to create specific beans for datasource and jdbctemplate while dealing with jdbctemplate in spring boot.

Let us quickly start with the code by defining our maven dependencies first.

Maven Dependencies

spring-boot-starter-parent: provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies.

spring-boot-starter-jdbc: provides all the maven dependecies for using JDBC with the Tomcat JDBC connection pool.

<properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

Spring Bean Configuration
package com.devglan.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.devglan") @SpringBootApplication public class Application { public static void main(String[] args) {, args); } }

Following is the model class with getters and setters.
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) { = id; } public String getName() { return name; } public void setName(String 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) { = email; } }

Now let us define our properties class which will be considered by spring-boot automatically to create the bean for datasource at run time.

spring.datasource.url=jdbc:mysql://localhost/devglan spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Now let us define our Dao class which will have implementation of jdbctemplate to insert rows in the db.We are using KeyHolder to hold the auto generated primary key.

package com.devglan.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import; import; import com.devglan.model.User; public class UserDaoImpl { private final String INSERT_SQL = "INSERT INTO USERS(name,address,email) values(?,?,?)"; @Autowired private JdbcTemplate jdbcTemplate; public User create(final User user) { KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getName()); ps.setString(2, user.getAddress()); ps.setString(3, user.getEmail()); return ps; } }, holder); int newUserId = holder.getKey().intValue(); user.setId(newUserId); return user; } }

Now, it is time to define our test cases to test whether the insert record in database with spring boot jdbctemplate.If you need to learn more on spring Boot Junit integration, then visit my earlier post Spring Boot Junit Integration Example
package com.devglan.dao.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.devglan.config.Application; import com.devglan.dao.UserDao; import com.devglan.model.User; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration (Application.class) public class UserDaoTest { @Autowired private UserDao userDao; @Test public void createUser() { User savedUser = userDao.create(getUser()); User userFromDb = userDao.findUserById(savedUser.getId()); assertEquals(savedUser.getName(), userFromDb.getName()); assertEquals(savedUser.getEmail(), userFromDb.getEmail()); } private User getUser() { User user = new User(); user.setAddress("Bangalore, Karnataka"); user.setEmail(""); user.setName("John Doe"); return user; } }


CREATE TABLE users (record_id bigint NOT NULL AUTO_INCREMENT, name varchar(100), address varchar(250), email varchar(100), PRIMARY KEY (record_id));

Run Application

Run the test case defined as Junit test case and check the result.You can also verify that a single user row is created in db.


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.

Download the source

Further Reading on Spring Jdbc

1. Insert Record In Db With Spring Boot Namedparameter Jdbctemplate

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

3. Working With Springboot Jdbctemplate

4. Working With Springboot Namedparameter Jdbctemplate

5. Execute Stored Procedure In Spring Jdbc

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