spring-bootSpring-Boot + JDBC


Introduction

Spring Boot can be used to build and persist a SQL Relational DataBase. You can choose to connect to an H2 in memory DataBase using Spring Boot, or perhaps choose to connect to MySql DataBase, it's completely your choice. If you want to conduct CRUD operations against your DB you can do it using JdbcTemplate bean, this bean will automatically bean be provided by Spring Boot. Spring Boot will help you by providing auto configuration of some commonly used beans related to JDBC.

Remarks

In order to get started, in your sts eclipse go to new --> Spring Starter Project --> fill in your Maven coordinates --> and add the next dependencies:

Under SQL tab --> add JDBC + add MySql (if MySql is your choice).

For Mysql you'll also need to add the MySql Java Connector.

In you Spring Boot application.properties file (you Spring Boot configuration file) you'll need to configure your Data Source credentials to MySql DB:

  1. spring.datasource.url
  2. spring.datasource.username
  3. spring.datasource.password
  4. spring.datasource.driver-class-name

for example:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Under the resources folder add the next two files:

  1. schema.sql --> every time you run your application Spring Boot will run this file, inside it you suppose to write your DB schema, define tables and their relationships.

  2. data.sql --> every time you run your application Spring Boot will run this file, inside it, you suppose to write data that will be inserted into your table as an initial initialization.

Spring Boot will provide you JdbcTemplate bean automatically so you can instantly can you use it like this:

@Autowired
private JdbcTemplate template;

without any other configurations.