Spring Boot JDBC

Most springboot projects are going with either Hibernate, JPA, or Spring Data. If you are still using JDBC to communicate directly with the database then this tutorial is for you.

Step 1 – Add this dependency to your springboot project

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

Step 2 – Add your data source configuration to your application.properties file.

# database
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_jdbc?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.name=spring_boot_jdbc
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Step 3 – Auto wire an instance of JdbcTemplate

@Autowired
private JdbcTemplate jdbcTemplate;

Create a method to create tables.

public void setup() {
		jdbcTemplate.execute(
				"CREATE TABLE IF NOT EXISTS member(id bigint(20) NOT NULL AUTO_INCREMENT, email varchar(255) NOT NULL, password varchar(255) NOT NULL, uid varchar(255) NOT NULL, PRIMARY KEY (`id`))");
}

INSERT operation

public User create(User user) {
		StringBuilder query = new StringBuilder("INSERT INTO member(uid, email, password) VALUES (?, ?, ?)");
		KeyHolder keyHolder = new GeneratedKeyHolder();

		jdbcTemplate.update(connection -> {
			PreparedStatement ps = connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

			ps.setString(1, user.getUid());
			ps.setString(2, user.getEmail());
			ps.setString(3, user.getPassword());
			return ps;
			
		}, keyHolder);

		long id = keyHolder.getKey().longValue();

		user.setId(id);

		return user;
}

It is just that simple to get up and running with JdbcTemplate in springboot.

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.