Spring Boot with H2 Database: A Practical Example

 

Spring Boot with H2 Database: A Practical Example

Spring Boot is a powerful framework that simplifies the development of Spring-based applications. One of its features is seamless integration with various databases, including H2, an in-memory database that is especially useful for testing and development purposes. In this article, we'll explore how to set up a Spring Boot application with H2 Database using a practical example.

Prerequisites

  1. Java Development Kit (JDK): Ensure you have JDK 11 or later installed.
  2. Maven: This example uses Maven for dependency management. You can also use Gradle if preferred.
  3. IDE: An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.

Step 1: Create a New Spring Boot Project

You can create a new Spring Boot project using Spring Initializr:

  1. Go to Spring Initializr.
  2. Choose the following options:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 3.4.0 (or the latest stable version)
    • Group: com.example
    • Artifact: springboot-h2-example
    • Name: springboot-h2-example
    • Packaging: Jar
    • Java: 11 or later
  3. Add the following dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database
  4. Click Generate to download the project zip file.
  5. Extract the zip file and open it in your IDE.

Step 2: Configure the H2 Database

Spring Boot auto-configures the H2 database, but you can customize the configuration if needed. Open src/main/resources/application.properties and add the following properties:

properties
# H2 Database configuration spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password # JPA Configuration spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # H2 Console configuration spring.h2.console.enabled=true spring.h2.console.path=/h2-console

This configuration sets up an in-memory H2 database and enables the H2 web console for easy access.

Step 3: Create an Entity

In Spring Data JPA, entities represent database tables. Create a new Java class to represent an entity. For example, let's create a Person entity:

java
package com.example.springboot.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

Step 4: Create a Repository

The repository interface provides CRUD operations for the Person entity. Create a new interface that extends JpaRepository:

java
package com.example.springboot.repository; import com.example.springboot.model.Person; import org.springframework.data.jpa.repository.JpaRepository; public interface PersonRepository extends JpaRepository<Person, Long> { }

Step 5: Create a Service

The service layer contains the business logic. Create a service class to handle operations related to Person:

java
package com.example.springboot.service; import com.example.springboot.model.Person; import com.example.springboot.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PersonService { @Autowired private PersonRepository personRepository; public List<Person> getAllPersons() { return personRepository.findAll(); } public Person savePerson(Person person) { return personRepository.save(person); } }

Step 6: Create a Controller

The controller handles HTTP requests and responses. Create a REST controller to expose endpoints for Person operations:

java
package com.example.springboot.controller; import com.example.springboot.model.Person; import com.example.springboot.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/persons") public class PersonController { @Autowired private PersonService personService; @GetMapping public List<Person> getAllPersons() { return personService.getAllPersons(); } @PostMapping public Person createPerson(@RequestBody Person person) { return personService.savePerson(person); } }

Step 7: Run the Application

Run the Spring Boot application by executing the main method in the SpringbootH2ExampleApplication class. The application will start up, and you can access the H2 console at http://localhost:8080/h2-console.

Step 8: Test the Application

You can test the application using tools like Postman or cURL:

  1. Add a Person:

    bash
    curl -X POST http://localhost:8080/persons -H "Content-Type: application/json" -d '{"name":"John Doe","age":30}'
  2. Retrieve All Persons:

    bash
    curl http://localhost:8080/persons

Conclusion

In this example, we demonstrated how to set up a Spring Boot application with H2 Database. This configuration is ideal for development and testing. For production environments, you would typically use a different database, such as MySQL or PostgreSQL. With Spring Boot's ease of configuration and H2's simplicity, you can quickly create and test applications without the overhead of managing a full database server.

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation