There are various ways in which we can initialize the database. Mostly for testing purposes I find setting hibernate.ddl-auto to create-drop with CommandLineRunner bean to save entities the most convenient. For this exercise let us use the H2 database, which we already had when we created the project.
[open pom.xml]
Let us run the app and open the URL localhost:8080/h2-console. Here we can see that our entities were auto-generated. This is accessible because we have set spring.h2.console.enabled to true (which is the default) in the application.properties file.
[open application.properties file]
How do we populate the database?
[open LoadDatabase class]
First, of the approach we will discuss is by using the CommandLineRunner bean and here is how it looks like. It accepts repository classes as parameters and returns a Lambda function where we define and save the entities.
Let’s take a look again at the h2-console and execute a query.
- Spring Repository Unit Testing
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactAlright. Now that we have a set of repository classes. I believe it’s a good time to introduce unit testing. Remember,...
- Working With Spring Data Repositories
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactJust like what we did with the entities the same approach can be used when creating the repository classes. And that...
- Database Modelling And Tools
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactIn this part, we will discuss the tools that we can use in designing our database. We will also create a database schema...
- Committing The Source Code On Github
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactTo commit our project in Github, make sure you already created a new Github repository and then: Get the repository...
- Create A Restful Web Service In Spring
Slack Discussion Repositories https://github.com/terawarehouse/terawarehouse-cataloghttps://github.com/terawarehouse/terawarehouse-reactTo prepare the project from future development, we will be creating a multi-maven project layout. Unfortunately,...