TODO List Project - JPA and Hibernate

previous_step

Connecting Spring Boot RESTful API with JPA and Hibernate

The awesome thing with JPA hibernate, spring hibernate, and springboot combination with H2 is the fact that as soon as you creae an entity, it would create the database in memory automatically.

In our project, to use JPA and Hibernate the injected dependency is spring-boot-starter-data-jpa and h2.

1. Setting up Todo Entity and Populating Data

  • Editing the Entity class

    • Add decorate @Entity above the class Todo. Then Todo would become an entity and would be stored into the database.

    • Indicate primariy key using @Id. Every entity in JPA needs to have a primary key. Another important thing is ID field ideally should be a wrapper class, so we use Long instead of long. It’s not suggested to have a primitive, because typically null indicates that an entity is not yet stored to the database. So what we are doing is we are making this Long.

    • Using @GeneratedValue above id, since we want that id to be automatically increased.

  • In application.properties, add more property related to JPA, hibernate, h2 and spring data jpa.

spring.jpa.show-sql=true
spring.h2.console.enabled=true
  • Then, start our application and type in URL localhost:8080/h2-console. We can see a console like this, change the JDBC URL to be jdbc:h2:mem:testdb and click Connect buttion.

    Now we can see the db console as follows.
  • Next, insert several data into the database in spring. Under folder src/main/resources, we create a new file data.sql and writh some sql statements.

INSERT INTO todo(id, username, description, target_date, is_done)
VALUES (10001, 'Lux', 'date with EZReal', sysdate(), false);

INSERT INTO todo(id, username, description, target_date, is_done)
VALUES (10002, 'Lux', 'practice Q', sysdate(), false);

INSERT INTO todo(id, username, description, target_date, is_done)
VALUES (10003, 'Lux', 'practice placing wards', sysdate(), false);

After restarting the server, we can see in the h2-console the data has been inserted into the todo table.

2. Connecting GET REST APIs to JPA Repository

  • Create a class TodoJpaRepository.
@Repository
public interface TodoJpaRepository extends JpaRepository<Todo, Long>{}
  • Create a class TodoJpaService and edit find todo by id method. Since the return type of method todoRepository.findById(id) is Optional, if we want to return a Todo, we use .get() method.
public class TodoJPAResource {

  @Autowired
  private TodoJpaRepository todoJpaRepository;

  @GetMapping("/jpa/users/{username}/todos/{id}")
  public Todo getTodo(@PathVariable String username, @PathVariable long id) {
      return todoJpaRepository.findById(id).get();
  }
}
  • Find todo list by username method. First, add a method in TodoJpaRepository.
@Repository
public interface TodoJpaRepository extends JpaRepository<Todo, Long>{
    List<Todo> findByUsername(String username);
}
@GetMapping("/jpa/users/{username}/todos")
public List<Todo> getAllTodos(@PathVariable String username) {
  return todoJpaRepository.findByUsername(username);
}
  • Change the URL in the frontend, we can add a new URL in app.constans.ts. That is export const TODO_JAP_API_URL = "http://localhost:8080/jpa".

3. Connecting POST, PUT and DELETE REST APIs to JPA Repository

  • Code backend. Note that when creating a new todo, we need to set username.
CLICK
@DeleteMapping("/jpa/users/{username}/todos/{id}")
public ResponseEntity<Void> deleteTodo (@PathVariable String username, @PathVariable long id) {

  todoJpaRepository.deleteById(id);

  return ResponseEntity.noContent().build();
}

@PutMapping("/jpa/users/{username}/todos/{id}")
public ResponseEntity<Todo> updateTodo(@PathVariable String username, @PathVariable long id, @RequestBody Todo todo) {

  Todo todoUpdated = todoJpaRepository.save(todo);

  return new ResponseEntity<Todo>(todo, HttpStatus.OK);
}

@PostMapping("/jpa/users/{username}/todos")
public ResponseEntity<Void> createTodo(@PathVariable String username, @RequestBody Todo todo) {

  todo.setUsername(username);
  Todo createdTodo = todoJpaRepository.save(todo);

  //Location
  //Get current resource url
  URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdTodo.getId()).toUri();

  return ResponseEntity.created(uri).build();
}
  • Change URL in frontend.

   Reprint policy


《TODO List Project - JPA and Hibernate》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC