Skip to main content

Getting Started with H2 Database: Installation, Configuration, and Usage Guide for Java Developers

Using H2 Database with Spring Boot

H2 is a lightweight, embeddable database engine written in Java. It can be used as an in-memory database, or as a persistent database stored on disk. In this post, we'll look at how to use H2 in a Spring Boot project.

Step 1: Add H2 Dependency

The first step is to add the H2 dependency to your project. If you're using Maven, add the following dependency to your pom.xml file:


	<dependency>
	    <groupId>com.h2database</groupId>
	    <artifactId>h2</artifactId>
	    <scope>runtime</scope>
	</dependency>
	

If you're using Gradle, add the following dependency to your build.gradle file:


	runtimeOnly 'com.h2database:h2'
	

Step 2: Configure H2 in your Spring Boot application

Next, you need to configure H2 in your Spring Boot application. This can be done by adding the following configuration properties to your application.properties file:


	spring.h2.console.enabled=true
	spring.datasource.url=jdbc:h2:mem:testdb
	spring.datasource.driverClassName=org.h2.Driver
	spring.datasource.username=sa
	spring.datasource.password=
	

The spring.h2.console.enabled=true property enables the H2 console, which provides a web-based interface for interacting with the database. The spring.datasource.url property specifies the JDBC URL for connecting to the database. In this example, we're using an in-memory database with the name testdb. The spring.datasource.driverClassName property specifies the JDBC driver class for H2. Finally, the spring.datasource.username and spring.datasource.password properties specify the database username and password. In this example, we're using the default username of sa and an empty password.

Step 3: Create Entity Classes

With H2 configured, you can now create entity classes for your database tables.Assuming you already have some knowledge of creating entity classes in Spring Boot, we'll create a simple Customer entity class to use as an example:


package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

This `Customer` class defines a simple entity with three fields: an `id` field that's automatically generated by the database, a `firstName` field, and a `lastName` field.

Step 4: Create a Repository Interface

Next, you'll need to create a repository interface to handle database operations for your `Customer` entity. This can be done using Spring Data JPA. Create a new interface called `CustomerRepository`:


package com.example.demo;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

}

This `CustomerRepository` interface extends the `CrudRepository` interface, which provides basic CRUD (create, read, update, delete) operations for your entity. You can add additional methods to this interface if you need to perform more complex queries.

Step 5: Test Your Application

With your entity and repository classes created, you can now test your application. Start your Spring Boot application, and navigate to `http://localhost:8080/h2-console` in your web browser. You should see the H2 console login page

Enter the JDBC URL, username, and password that you specified in your `application.properties` file, and click "Connect". You should see the H2 console interface

From here, you can execute SQL queries, view table data, and perform other operations on your database. To test your `CustomerRepository`, open a new tab or window in your web browser, and navigate to `http://localhost:8080/customers`. You should see an empty JSON array:

[

]

To add a new customer, you can use the `curl` command-line tool or an HTTP client like Postman. Here's an example `curl` command to add a new customer:

curl -X POST \
  http://localhost:8080/customers \
  -H 'Content-Type: application/json' \
  -d '{
    "firstName": "John",
    "lastName": "Doe"
  }'

After executing this command, refresh the `http://localhost:8080/customers` page in your web browser, and you should see the new customer:

[
  {
    "id": 1,
    "firstName": "John",
    "lastName":"Doe"
}
]

Congratulations, you've successfully set up and tested H2 database integration in your Spring Boot application!

Conclusion

Using an in-memory database like H2 can be a great option for development and testing in your Spring Boot applications. With its simple setup and easy-to-use console interface, it's a convenient way to get started with database-driven development. By following the steps outlined in this tutorial, you should be able to quickly integrate H2 into your Spring Boot project and start building database-backed applications.

If you want to learn more about Spring Boot and database integration, there are many resources available online, including the official Spring Boot documentation, blogs, and tutorials. Happy coding!

References

Comments

Popular posts from this blog

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...