Unit test

The findById() method can be used to query using the primary key. The following snippet shows an example:

    @Test    public void findOne() {      Optional<Todo> todo = todoRepository.findById(101L);      assertEquals("Todo Desc 1", todo.get().getDescription());    }

Optional represents a container object for an object that can be null. Some of the important methods in Optional are listed below:

  • isPresent(): Check if Optional contains a non-null value.
  • orElse(): Default value if the object contained is null.
  • ifPresent(): Code in ifPresent is executed if the object contained is not null.
  • get(): To retrieve the contained object.

The existsById() method can be used to check whether an entity with the given ID exists. The following example shows how ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.