DEV Community

Piyush Kulkarni
Piyush Kulkarni

Posted on AI-assisted

Spring boot learning by doing

In a previous post, I used a linked list to create a CRUD application. However, to save data permanently, a linked list is not sufficient; you need to utilize a database, which will allow data to persist even after closing the application.

As a beginner, I opted for the H2 in-memory database. This choice was made to avoid the need to download and configure a full relational database like MySQL or PostgreSQL, making the setup easier. I plan to switch to a more robust database in the future.

Configuring the H2 In-memory Database

In the application.properties file, you will add three grouped configurations:

  1. H2 Database Configuration: This setup creates an in-memory database, meaning the database resides in your RAM.

  2. JPA Configuration: What is JPA (Jakarta Persistence API)? Instead of writing SQL queries manually, you can write Java code, and JPA will translate it into SQL queries to be executed on the database.

  3. H2 Database Console Configuration: This provides a visual representation of your in-memory database, accessible via a web browser, typically at http://localhost:8080/h2-console.

Here are the configurations you would include in the application.properties file:

spring.application.name=demo
server.port=8080

# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:taskdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

# JPA Configuration
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# H2 Console Configuration
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Enter fullscreen mode Exit fullscreen mode

The URL is used to create the database for you, while the driver class connects your application to the database. The username and password are the credentials required to access the database.

The "dialect" varies for each relational DBMS (Database Management System). Although they all use SQL, the syntax can differ slightly among different DBMS software. Thus, while the language remains the same, the dialect is different, which is why it's essential to specify the particular dialect for which JPA (Java Persistence API) will generate queries.

Setting ddl-auto=update allows your database to be updated according to the entity classes defined in your application. The show-sql option lets you view the SQL queries generated by JPA in the terminal.

This configuration will allow you to work with an H2 in-memory database effectively, providing both ease of use and accessibility for development purposes. Please remember to add the Spring Data JPA dependency in the pom.xml file.

Top comments (0)