Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - H2 Database

The H2 database is an in-memory and embedded database, which is often used in development and testing environments because of its lightweight nature, easy setup, and fast performance. It's also useful for proof-of-concept projects or when you need a simple persistent storage without setting up a standalone database.

When integrated with Spring Boot, the H2 database provides automatic configuration and an easy-to-use console to view and query the database content. Here's a step-by-step guide to integrating and using the H2 database with Spring Boot:

1. Add Dependencies:

First, add the required dependencies in your pom.xml (if you are using Maven):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. Configuration:

Modify your application.properties or application.yml file to configure H2 and enable the H2 console:

# Enabling H2 Console
spring.h2.console.enabled=true

# Datasource Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

3. Entity and Repository:

You can now define JPA entities and repositories just like you would with any other database.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    // getters, setters, constructors...
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

4. Accessing the H2 Console:

Once your Spring Boot application is running, you can access the H2 console via:

http://localhost:8080/h2-console

Ensure that the JDBC URL in the console matches your configuration (jdbc:h2:mem:testdb in this case).

5. Populating Data:

If you want to populate your H2 database with some data at startup, you can create a data.sql file in the src/main/resources directory. Spring Boot will automatically execute this SQL file after the entities have been created.

For instance, if you want to insert a user at startup:

INSERT INTO user (name) VALUES ('John Doe');

6. Switching to File-based Storage:

By default, H2 operates in an in-memory mode, meaning data is lost once the application stops. If you want persistent storage, switch to file-based storage by modifying the datasource URL:

spring.datasource.url=jdbc:h2:file:/path/to/your/database/file

7. Production Considerations:

While H2 is excellent for development and testing:

  • It's generally not recommended for production use. Instead, consider more robust database systems like PostgreSQL, MySQL, or Oracle for production environments.
  • Ensure the H2 console is disabled in production to prevent potential security risks.

By following these steps, you can seamlessly integrate the H2 database with your Spring Boot application, facilitating rapid development and testing.

  1. Configuring H2 Database in Spring Boot:

    • Add H2 dependencies in your pom.xml or build.gradle.
    • Configure H2 properties in application.properties or application.yml.

    Example (application.properties):

    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=password
    spring.h2.console.enabled=true
    
  2. In-memory database usage in Spring Boot with H2:

    • Utilize the jdbc:h2:mem: URL for an in-memory H2 database.
    • Ideal for testing and development.

    Example (application.properties):

    spring.datasource.url=jdbc:h2:mem:testdb
    
  3. Creating tables and schemas in H2 Database with Spring Boot:

    • Define JPA entities with annotations.
    • Use Spring Data JPA repositories for CRUD operations.

    Example (User entity):

    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Entity
    public class User {
    
        @Id
        private Long id;
    
        // Other fields, getters, and setters
    }
    

    Example (UserRepository interface):

    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        // Custom queries if needed
    }
    
  4. H2 Console integration in Spring Boot applications:

    • Enable H2 Console through properties.
    • Access the H2 Console at /h2-console during development.

    Example (application.properties):

    spring.h2.console.enabled=true
    
  5. H2 Database persistence with Spring Data JPA in Spring Boot:

    • Leverage Spring Data JPA repositories for easy database operations.
    • Extend JpaRepository for basic CRUD operations.

    Example (UserService class):

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        // Service methods using userRepository
    }
    
  6. Data initialization and seed data with H2 in Spring Boot:

    • Use data.sql or schema.sql in the src/main/resources folder for initialization.
    • Define sample data to be loaded during application startup.

    Example (data.sql):

    INSERT INTO user (id, username, email) VALUES (1, 'john_doe', 'john@example.com');
    
  7. Testing with H2 Database in Spring Boot:

    • Use H2 for integration tests.
    • Configure application-test.properties or application-test.yml with H2 properties.

    Example (application-test.properties):

    spring.datasource.url=jdbc:h2:mem:testdb
    

    Example (Test class):

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
    
        // Write your test cases using H2 as the test database
    }