In this I would teach you how to save data to database using H2 database. Remember, that previously we have hardcoded the list of items. Later we used CrudRepository. But we don’t have nay initial data. In this lesson we would:
- add support for the H2 database (dependencies)
- access the H2 GUI (h2-console)
- write SQL query to add the initial data
First let me give you a brief overview of the H2 database.
About H2 In-Memory Database
First, an in-memory database is a database that resides in the classpath. That it in main memory, not in disk. H2 is called the Java SQL database. It is a relational database system written in Java. Therefore it is embeddable into Java applications. Other in memory databases includes:
- Apache Derb
Benefits of H2
- Open Source
- Faster than conventional RDBMS
- Provides a GUI called H2-Console accessible through the browser
Before we add support for H2, take a look at the architecture of the application to understand the relationship between Controller, Service and Repository:
Add Support for H2 Database
The first step is to add the support for the H2 database. Now, H2 is an in-memory database that resides in the class path.
- Add the following dependencies to the pom.xml
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
2. Add the following to the application.properties file
spring.h2.console.enabled=true spring.jpa.hibernate.ddl-auto=update spring.datasource.platform=h2 spring.datasource.url=jdbc:h2:mem:socialdb
3. Test the application.
4. Go to http://localhost:8080/h2-console. You will get the H2 Console login window as shown below.
5. Make sure that the JDBC URL is set correctly. The name of the database should be the same as the one specified in the application.properties file.
6. Click on Test Connection.
7. Then click on Connect. The database console opens as shown below
To take the next step, you have to stop the server
8. Create a file in the src/main/resources folder named data.sql.
9. Write queries to insert some initial data into the locations table. The content is as below.
10. Then save the file. Then relaunch the application. Access the H2 Console and check that the data is inserted into the database.
11. Next try to use the Edit button in the H2 Console to add some records into the database
We are not done yet!
In the next lesson we would continue with relationships and query methods. Fell free to watch the video if you miss something. Also try to reach me if you have some challenges following the lesson. Leave a comment in the video comment section.