Spring Boot allows you to connect a database simply with minimal configuration. Let’s see in this post how to connect to a database.
How to connect Spring Boot with database
You can create a database connection in Spring Boot with a few steps.
- Define the database you are going to use.
- Include dependencies.
- Define connection settings in the property file.
Define the database
In this example, we will use MySql, but the configuration applies to any database.
The only difference is the dependency necessary to connect your database with your service.
Dependencies to create a database connection in Spring Boot
To create a DB connection, you need the following dependencies.
For MySql you need:
Database connection settings in the property File
In these properties, we first set the connection path to the DB. Then we indicate the user and the password. With this minimal configuration and the dependency, it is enough for Spring to understand how to connect.
The minimum configuration to connect to a database is as follows:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=your_user spring.datasource.password=your_password
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database spring.datasource.username=your_user spring.datasource.password=your_password
spring.datasource.url=jdbc:oracle://localhost:1521/your_database spring.datasource.username=your_user spring.datasource.password=your_password
spring.datasource.url=jdbc:sqlserver://localhost:1433/your_database spring.datasource.username=your_user spring.datasource.password=your_password
*Note that the port and url may change depending on the installation of each database.
Spring can create the tables for you
If you want to delegate the creation of tables to Spring you can do it adding one property.
This setting tells Spring whether to create the tables from the entities we have created.
This article explains more about this property.
- none: no action will be performed.
- drop: the tables will be created from the entities and at the end, they will be deleted.
- create: the tables will be deleted and then created
- update: performs an update of the schema from the entities.
- validate: only performs a validation between the entities and the database schema.
Let’s zoom in on this property “spring.jpa.hibernate.ddl-auto”
If we define this property as “create” Spring will destroy all tables and then create all of them.
In order to understand more about entities, review this other post
For example for this entity. Spring will do the following
Observe in the Spring console what happens with this “create” configuration.
In order to see the Spring SQL sentences in the console, you need this configuration
In this post, we learn how to configure a connection to a database and how to delegate the creation of database/tables to Spring.