spring boot spring data jpa h2 database crud example

 

spring boot spring data jpa h2 database crud example tutorial that explains how to create a REST api using Spring boot 2, Spring data jpa and h2 database.

This tutorial is an enhancement of the tutorial that creates a restful webservice using an arrayList as our datasource.

Adding Spring data JPA and h2 database maven dependencies

H2 is an in memory database used for integration testing when we want to test the real endpoint and we don’t want to hit the real database (if we stop the application, we will loose the data stored in the H2 database).

We should be able to replay the tests during the build. So, we add the data used for the tests before running the tests and we don’t depend on the data present in the real database.

We will deal with unit and integration testing of restful webservices in a future tutorial, so please stay tuned.

The dependencies to be added to the maven POM file are the followings :

<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>

Setting up H2 database using the application.properties file

In the application.properties files, we provide the connection url, the jdbc driver, the username, the password and all the database settings.

The database settings are the followings :

spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=abderrahmen
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Here the database name is mydb.

We can make the database persistent and not volatile by using a file to store the data.

In this case, we need to change the connection URL to be like this :

spring.datasource.url=jdbc:h2:file:/data/mydb

In order to make Spring Boot create the table used in this tutorial, we add a file in src/main/resources.This file is the data.sql file and its content is the following :

DROP TABLE IF EXISTS todo;

CREATE TABLE todo (
  id INT AUTO_INCREMENT  PRIMARY KEY,
  name VARCHAR(250) NOT NULL,
  description VARCHAR(250) NOT NULL
);

Accessing H2 database console

H2 database has an embedded UI that allows to run SQL queries and manage the database.

This UI is called the H2 database console. In order to enable this console, we should add this line in the application.properties file :

spring.h2.console.enabled=true

Then, we should run the application and access this URL in the browser :

http://localhost:8080/h2-console


h2 database console

Here, we make sure that the JDBC URL is correct. Then, we put the password present in the application.properties and we click on the connect button.

The JDBC URL and the password should be the ones present in the application.properties file.

After clicking on the connect button, we should see this interface :

h2 database console run sql

Now, we should see the TODO table created on the application startup.

Updating the REST API to use H2 database

In order to update the Spring BootREST API example, we will :

  • Update the model to add JPA annotations
  • Create a new repository that makes the CRUD operations
  • Create a new service that uses this repository
  • Update the controller to use this service

Rest API Model

We will add the JPA annotations to the Todo entity in order to make it managed by Spring Data JPA.

The required annotations are :

  • @Entity : to make the class a JPA entity
  • @Id : to make a field a primary key
  • @GeneratedValue : to make the id auto-incremented

In this class, we can get rid of Getters, Setters and constructors by using lombok. But, i don’t do it for the sake of simplicity and to make the beginners understand the code.

The code of the class is the following :

package com.javasneo.todolist.model;

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

@Entity
public class Todo {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
  private String name;
  private String description;

  public Todo() {
  }

  public Todo(int id, String name, String description) {
    this.id = id;
    this.name = name;
    this.description = description;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setDescription(String description) {
    this.description = description;
  }
}

Rest API Repository

The repository is a java interface with no java class implementing it. This is a spring Data JPA feature that auto-generates the CRUD code for us based on an interface that we specify.

The code of the repository is the following :

package com.javasneo.todolist.repository;

import com.javasneo.todolist.model.Todo;
import org.springframework.data.repository.CrudRepository;

public interface TodoRepository extends CrudRepository<Todo, Integer> {
}

The TodoRepository interface should extend the Spring Data JPA interface CrudRepository and give two parameters to that interface :

  • The first one is the Type of the Entity that we will generate the CRUD code for.
  • The second one is the type of the primary key of the entity (the id attribute in the Todo class is of type Integer)
Rest API Service

The service layer of the application is composed by the interface of the service and its implementation.

The source code of the interface is the following :

package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;

import java.util.List;

public interface TodoService {
  List<Todo> getAll();
  Todo saveOrUpdate(Todo todo);
  void delete(int id);
}
The source code of the implementation is the following :
package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TodoServiceImpl implements TodoService{
  @Autowired
  TodoRepository todoRepository;

  public List<Todo> getAll(){
    List<Todo> todoList = new ArrayList<Todo>();
    todoRepository.findAll().forEach(todo -> todoList.add(todo));
    return todoList;
  }

  public Todo saveOrUpdate(Todo todo)
  {
    return todoRepository.save(todo);
  }

  public void delete(int id)
  {
    todoRepository.deleteById(id);
  }

}

Rest API controller

The controller uses the service layer to provide the CRUD endpoints.

The source code of the controller is the following :

package com.javasneo.todolist.controller;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.model.TodoListResponse;
import com.javasneo.todolist.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/todos")
@CrossOrigin()
public class TodoController {

  @Autowired
  TodoService todoService;

  @RequestMapping(method = RequestMethod.GET)
  public TodoListResponse todos (){
    List<Todo> todoList = todoService.getAll();
    TodoListResponse todoListResponse = new TodoListResponse();
    todoListResponse.setTodos(todoList);
    return todoListResponse;
  }

  @RequestMapping(method = RequestMethod.POST)
  public Todo addtodo (@RequestBody Todo todo){
    return todoService.saveOrUpdate(todo);
  }

  @RequestMapping(method = RequestMethod.PUT)
  public Todo updateTodo (@RequestBody Todo todo){
    return todoService.saveOrUpdate(todo);
  }

  @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
  public void deleteTodo (@PathVariable("id") int id){
    todoService.delete(id);
  }

}
 

Conclusion

this spring boot spring data jpa h2 database crud example tutorial arrives at its end.

If you want to know how to test the endpoints using Postman, please check the part 1 of these series of tutorials that deal with Spring Boot 2 RESTAPI.

You may check also our core java tutorial to learn core java from scratch. Please keep tuned because we will release more tutorials about Spring Boot, unit testing, integration testing and other important subjects.

In order to get our latest updates, please feel free to like our how toprogram facebook page.

The source code can be found in abderrahmen ben mariem github.

Post a Comment

Previous Post Next Post