Practice Efficient Java development with H2 SQL Database

Time is limited. That’s why it’s important to use it wisely. Programming is the art of finding solutions, and technology provides us with the tools to do so.
Today I want to introduce you to H2 Database, a system that will speed up your development process, by providing you an in-memory SQL database, easy to set set-up and ready to be used in your project.
Especially during the early stage of software development, this technology will help you set up a prototype, test different solutions, and deliver a clustered program that will greatly improve your efficiency.

At the end of this guide, you will be ready/able to implement an H2 database in your project.

We will create a simple Spring Rest project that uses H2 to simulate the persistence side.

H2 database is supported by the Spring Boot initializer. It can also be added to an existing project by adding the following dependency to your pom.xml.

Moving forward, you can build your own version or follow my solution by downloading this project from my GitHub repository.

Once you have the project opened in your favorite ide, set up an Entity, and a Repository that we will use to test our database.

After you have done that, it’s time to add a few lines to our

Before running the project, we can add a data.sql file in the resources folder in order to populate the soon-to-be-created database with some values.

Now it’s time to press the run button and enjoy your new project.

To verify the program is reading the database go to http://localhost:8080/beers and you will find something like this.

This means that the software is working and it’s giving you the results of the get request as intended.

But, how is that working?
H2 under the hood creates a database that has a console and is accessible by visiting http://localhost:8080/h2-console

Here you will be able to execute all the queries you may need for your program development and observe the results as you would in a traditional SQL database.

Let’s add a new item to our database and check again the REST Get results.
It works as intended.

But remember, once you restart the program, it will be restored to the values you prepared in your data.sql, that’s because it’s an in-memory database. Great for testing and developing, not for the production release.

We have seen how to set up and play a bit with the H2 console.
This tool will allow you to be faster and more focused on your development process.
As the spaniards say, ¡ahora sácale provecho!
Happy developing.

Full Stack developer - Java enthusiasts - Docker lover - Ironhacker and 42 - Jurist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store